!(function(){
    var __functionForGrid=function (Ladder) {
        Ladder.include([Ladder.BasicURL + "/css/ladder-datagrid.css"]);
        Ladder.NS("DataGrid");
        /**
         * ###  数据表格是YUI的重要组成部分，主要功能有:模版定制，数据显示，多列合并，分页，首行冻结，多表头，导出，数据过滤，字段订阅，列排序，手动列宽,数据统计，子集树形
         *     @example
         *      1)基本用法
         var dg=new Ladder.DataGrid('#gird', {
               queryUrl: URLS.URL_BasicQueryData,
               queryData: { tableName: 'dd', psize: 18},
               columnAlign: 'center',
               saveUrl: URLS.URL_BasicSaveBean,
              titleRowHeight: 30,
               title: "数据字典",
               queryFormAction:'auto|button',
               sorter:true,
               layoutH:0,
               saveExter: { tableName: 'dd' },
               fitView:'pager,queryform,button,caption,setting,export,default,',
               thType:0, //0:自动模式，1:表格一体表头,2:为冻结表头,1:为自定义表头
            });
         dg.loadRemote();

         *      2）自动统计功能
         *
         var dg=new Ladder.DataGrid("#grid",{
                queryUrl: URLS.URL_BasicQueryData,
                queryData: { tableName: "postlistSql", condition: condition },
                fitView: "pager|caption,counter",
                layoutH: 0,
                columnAlign:'center'
            });
         dg.setColumnConfig("braid,count",{counter:true});
         dg.setColumnConfig("id,postitemid,did,aid",{isshow:false,columnAlign:"center"});
         dg.addExtColumn({
                title:"差异化",
                index:5,
                counter:true,
                callback:function(r,rr,rrr){
                    var diff=rrr.count-rrr.braid;
                    if(diff===0)return "0"
                    return diff;
                }
            });
         dg.loadRemote();


         * @constructor
         */
        Ladder.DataGrid = function () {
            //获取变体参数start
            var el, option, fullWidget;
            for (var i = 0; i < arguments.length; i++) {
                var type = Ladder.getType(arguments[i]);
                if (type == "Object") {
                    if (arguments[i] instanceof $) {
                        el = arguments[i];
                    } else {
                        option = arguments[i];
                    }
                }
                if (type == "Boolean") fullWidget = arguments[i];
                if (type == "String") el = arguments[i];
            }
            if (el != undefined) {
                if (option == undefined) option = new Object();
                option.datagridEL = el;
            }
            if (option==undefined)return;
            if (Ladder.getType(option) != "Object") return;
            if (fullWidget != undefined) option.fullWidget = fullWidget;

            //获取变体参数end
            //配置项，运行数据参数等start
            this.settings={
                /**@cfg {Boolean}全局标识*/
                id:"datagrid",
                /**@cfg {Boolean}多行选择*/
                multiLine: true,
                /**@cfg {Boolean}排序*/
                sorter: option.sort||option.sorter||true,
                /**@cfg {Boolean}手动调宽 2015-7-26默认禁用*/
                resizable: false,
                /**@cfg {String} 表格的样式*/
                gridClass: 'yui-datagrid-table',
                /**@cfg {String} 表格当前行的样式*/
                selectClass: 'currentSelect',
                /**@cfg {Boolean} 列模型是否自动*/
                autoColumnModel: true,
                /**@cfg {Number} 默认宽度->2015-7-23交由css和父级元素控制*/
                width: "100%",
                /**@cfg {Number} 默认高度->2015-7-23交由css和父级元素控制*/
                height: 500,
                /**@cfg {Number} 行高->2015-7-23交由css和父级元素控制*/
                /**@cfg {Number} 表格高度*/
                bodyHeight: false,
                /**@cfg {Number} 表格宽度*/
                bodyWidth:false,
                rowHeight: 25,
                /**@cfg {Number}标题行高*/
                titleRowHeight: 25,
                /**@cfg {Number}距底高度*/
                layoutH:false,
                /**@cfg {Boolean}充满整个表格*/
                full:true,
                /**@cfg {Number}冻结行数*/
                freeze:0,
                /**@cfg {String} 分页元素，如果是自定义的时候，由此属性扩展，如果是全功能表格，此处请不要赋值*/
                pageEL: '',
                /**@cfg {String} 表单元素，如果是自定义的时候，由此属性扩展，如果是全功能表格，此处请不要赋值*/
                queryFormEL: "",
                /**@cfg {String} 表单动作类型，
                 *
                 * - button：为点击按钮进行提交查询
                 * - auto：为内容改变提交查询 */
                queryFormAction: 'auto,button', //auto
                /**@cfg {String} 显示分页的数量*/
                pageShowNum: '10|20:selected|30|50|100',
                /**@cfg {String} 导出类型,auto page all*/
                exportType:"auto",
                /**@cfg {String} 父级元素*/
                parentEL: null,//父元素
                /**@cfg {String} 父级元素*/
                rollload:null,
                /**
                 * @cfg {Object} 阅读器
                 */
                reader: {
                    statusCodeText: { "200": "success", "400": "访问错误", "500": '数据服务出错' },//阅读器的状态码
                    statusCode: 'statusCode',//状态码阅读节点
                    pager: 'data.condition.pager',//分页阅读节点
                    columnModel: 'data.columns',//列模型节点
                    data: 'data.records',//具体数据阅读节点
                    condition: 'data.condition',//连续查询条件阅读节点
                    queryform: 'data.queryform',//简单查询表单阅读节点
                    fullcolumns: 'data.fullcolumns'//全字段阅读节点
                },
                /**@cfg {String} 列水平对齐*/
                columnAlign: 'center',
                /**@cfg {String} 列垂直对齐*/
                columnVAlign: 'middle',
                /**@event {Function} 分页事件-》当页面转移的时候*/
                onPaging: option.eventpage,
                /**@event {Function} 选择当前行事件*/
                onSelectRow:option.eventSelectRow,
                /**@event {Function} 行双击事件->function(me,tr),me是组件对象,tr是行对象*/
                onDblClick:option.eventdblclick,
                /**@event {Function} 数据加载完成事件,数据渲染完成事件*/
                onFinished:option.eventfinished,
                /**@event {Function} 表单查询之前事件*/
                onFormRender:null,
                /**@event {Function} 表单查询之前事件*/
                onQueryForm:option.eventqueryform,
                /**@event {Function} ajax请求之前*/
                onRequestBefore:null,
                /**@event {Function} 数据渲染之前事件*/
                onBefore:null,
                /**@event {Function} 离开选择行事件*/
                onRowLeave:null,
                /**@event {Function} checkbox选中后事件*/
                onCheck:null,
                queryUrl: null,//数据查询接口
                queryData: null,//数据查询参数
                saveUrl: null,//数据维护接口
                saveExter: null,//保存的扩展参数
                /**@cfg {String/Boolean}
                 * boolean:false->不出现选择
                 * boolean:true->多选，但数据在换页事不保存
                 * String:"only"->单选，换页时清空数据
                 * String:"keep"->在换页或数据置换的情况，依然保留依然保存数据
                 * */
                multiSelect: false,//false，0时不出现选择框，only时选择框为当选 ，其他值为多选
                /**
                 * @cfg 配置可选视图
                 *
                 * default 默认
                 * setting 设置按钮
                 * caption 标题
                 * queryform 条件查询
                 * button 头部按钮
                 * pager 分页
                 */
                fitView: "default",//setting，caption，queryform，button，pager,
                /**@cfg 表头类型
                 *
                 * 0为自动模式
                 * 1,表格一体表头
                 * 2,为冻结表头，
                 * -1，为自定义表头
                 * */
                thType: 0
            };
            /**表格模式，display|edit|tree|chart
             *
             * - display:显示模式
             * - edit:编辑模式*/
            this.gridModel="display";
            /**{Array}列模型*/
            this.columnModel=new Array(),//列模型
                /**{Object}列过滤器，实际上是为字段附加信息和替换信息的*/
                this.columnFilter= new Object()     /**{Array}扩展列模型，于普通列模型相似*/
            this.extColumnModel=null;
            /**{Array} 全字段模型*/
            this.fullColumns=null;
            /**{Array} 数据区*/
            this.griddata = null;
            /**{Object} 查询条件*/
            this.condition = {};//2015-10-19,null->{}
            /**{$el} 表格元素对象*/
            this.datagrid = null;
            /**{$el} 表格头部元素对象*/
            this.gridhead = null; //多表头
            /**{$el} 表格当前行元素对象*/
            this.selectRow = null;
            /**{Object} 子视图配置数据 **/
            this.subview=null;
            /**{Object} 已选择行对象*/
            this.multiSelectData=new Object();
            this.morequery=null;
            //运行期对象
            this.runstatus = {
                B_queryFrom: false, //queryform 是否填充 状态位
                THObject: null, //运行期表头的数据
                B_TH: false, //自定义表格是否初始化,
                ToLink: null, //外置链接，用于表格上转向和跳转
                /** 是否安装完成*/
                Install:false,
                /**状态***************/
                Status:0,
                TableModel:"datagrid",//表格模型
            };
            //配置项，运行数据参数等end
            //创建表格组件视图
            $.extend(this.settings,option);
            //var $a = $("<a href='#'></a>");
            var $a = $("<iframe style='display:none'></iframe>");
            this.runstatus.ToLink = $a;
            $(document.body).append($a);
            this.createGridView(this.settings);
        };
        Ladder.DataGrid.prototype = {
            getContainer:function(){
                return this.settings.parentEL;
            },
            /**
             * 创建表格视图，2015-10-17，是原inittable和createfullwidget的综合体
             * @private
             * @param option
             * @returns {*}
             */
            createGridView: function(option) {
                var me = this;
                if (!option) return;
                //整理父组件,置换选择器为父组件
                var $el = $(option.datagridEL); //参数传出的选择器
                if ($el.length < 1) return;
                me.settings.parentEL = $(option.datagridEL);
                if (option.fullWidget) {
                    me.settings.fitView = "default|queryform|button|columnresize|pager";
                    if (!me.settings.queryFormAction) me.settings.queryFormAction = "button";
                    //顶部视图
                    me.createHeadView($el, me.settings);
                    //表头(表格的标题头)，表体，以及附着载体
                    var dgthel = $('<table></table>').append("<thead></thead>").append("<tbody></tbody>");
                    $el.append($("<div class='yui-datagrid-th'></div>").append(dgthel));
                    this.gridhead = dgthel;
                    var gridhost = $("<div class='yui-datagrid-body'>" +
                        "<div class='yui-datagrid-body-container'>" +
                        "<div class='yui-datagrid-body-corner'></div>" +
                        "<div class='yui-datagrid-body-head'></div>" +
                        "<div class='yui-datagrid-body-columns'></div>" +
                        "<div class='yui-datagrid-body-data'></div>" +
                        "</div></div>"); //数据附在的表格元素
                    var dgbodyel = $('<table></table>').append("<thead></thead>").append("<tbody></tbody>");
                    me.settings.datagridEL = dgbodyel; //option.datagridEL和this.datagrid 是重叠属性,应用于inittable
                    this.datagrid = dgbodyel;
                    gridhost.find(".yui-datagrid-body-data").append(dgbodyel);
                    if (option.bodyHeight) gridhost.css("height", option.bodyHeight);
                    $el.append(gridhost);
                    $el.append("<div class='yui-datagrid-space'></div>");
                    me.createFootView($el, me.settings);
                    this.runstatus.TableModel = "datagrid";
                }
                if (!this.datagrid) {
                    var nodeName = ($el[0].nodeName).toLowerCase();
                    //如果是表格元素直接填充,如果div创建表格并拓展基本功能,如果其他替换成表格，不扩展
                    if (nodeName != "table") {
                        //主体内容表格
                        var newtable = $('<table></table>').append("<thead></thead>").append("<tbody></tbody>");
                        //表头table组件
                        var dgthel = $('<table></table>').append("<thead></thead>").append("<tbody></tbody>");
                        if (nodeName == "div") {
                            //创建头部
                            if (/(default)|(setting)|(caption)|(queryform)|(button)/i.test(option.fitView)) this.createHeadView($el, me.settings);
                            // //创建表格view
                            // var gridhead = $("<div class='yui-datagrid-th'></div>");
                            // gridhead.append(dgthel);
                            // $el.append(gridhead);
                            //数据表格包裹体
                            var gridhost = $("<div class='yui-datagrid-body'>" +
                                "<div class='yui-datagrid-body-container'>" +
                                "<div class='yui-datagrid-body-corner'></div>" +
                                "<div class='yui-datagrid-body-head'></div>" +
                                "<div class='yui-datagrid-body-columns'></div>" +
                                "<div class='yui-datagrid-body-data'>" +
                                "<div class='yui-datagrid-space'></div>"+
                                "</div>" +
                                "</div></div>");
                            gridhost.find(".yui-datagrid-body-data").prepend(newtable);
                            if (option.bodyHeight)gridhost.css("height", option.bodyHeight);
                            $el.append(gridhost);
//                        $el.append("<div class='yui-datagrid-space'></div>");
                            if (option.fitView == undefined) option.fitView = "default";
                            //创建尾部,2015-7-26,暂只创建分页
                            if (/(default)|(pager)/i.test(option.fitView))this.createFootView($el, option);

                        } else {
                            layer.msg("宿主元素正在替换", { icon: 2 });
                            $el.replaceWith(newtable.width($el.width()));
                        }
                        this.datagrid = newtable;
                        this.gridhead = dgthel;
                        this.runstatus.TableModel = "datagrid";
                        if (!this.datagrid) return;
                    } else { //是表格元素
                        this.runstatus.TableModel = "table";
                        this.datagrid = $el;
                        if(this.datagrid.find("thead").length<1)this.datagrid.prepend("<thead></thead>");
                        if(this.datagrid.find("tbody").length<1)this.datagrid.append("<tbody></tbody>");
                    }
                }
                //处理默认设置
                this.setTitleHeight(me.settings.titleRowHeight);
                if (this.runstatus.TableModel == "datagrid" && me.settings.gridClass)
                    this.datagrid.addClass(me.settings.gridClass);
                if (!me.settings.multiLine) me.datagrid.attr("unselectable", "on").attr("onselectstart", "return false;");
                me.settings.height = $el.height();
                me.settings.width = $el.width();

                if (me.settings.full)this.datagrid.attr("width", "100%");
                if (me.settings.bodyWidth) {
                    this.datagrid.attr("width", me.settings.bodyWidth).css("width", me.settings.bodyWidth);
                    me.settings.parentEL.find(".yui-datagrid-space").css("width", me.settings.bodyWidth);
                }
                //$el.wresize(function(){
                //    alert(111);
                //});
                //清空初始化的参数的存储
                if (me.settings.queryData && me.settings.queryData.hasOwnProperty("condition")) {
                    if (Ladder.getType(me.settings.queryData.condition) == "String")
                        me.condition = JSON.parse(me.settings.queryData.condition);
                    else me.condition = me.settings.queryData.condition;
                    delete me.settings.queryData.condition;
                }
                if (me.settings.queryData && me.settings.queryData.tableName) {
                    this.datagrid.attr("data-tableName", me.settings.queryData.tableName);
                }
                me.layoutSize();
                me.runstatus.Install = true;
                me.runstatus.Status = 1;
                //绑定事件
                //this.datagrid.off();
                //this.datagrid.find("tbody").find("tr").click(function () {
                //    me.selectRow = $(this);
                //    if(me.settings.onSelectRow) me.settings.onSelectRow();
                //    if (me.selectRow) me.selectRow.removeClass(me.settings.selectClass);
                //    me.selectRow.addClass(me.settings.selectClass);
                //});
            },
            /**
             * 获取和设置settings
             * @param name
             * @param value
             * @returns {*}
             */
            option: function(name, value) {
                if (name) {
                    if (value == undefined) {
                        return this.settings[name];
                    } else {
                        this.settings[name] = value;
                        return this.settings[name];
                    }
                } else {
                    return this.settings;
                }
            },
            /**
             * 设置组件宽度
             * @param w
             */
            setWidth: function(w) {
                if (this.datagrid) {
                    this.datagrid.css("width", w);
                    this.datagrid.resizableColumns();
                }
            },
            /**
             * 设置为显示模式
             * @param $tr
             */
            setDisplay: function($tr) {
                if (!$tr || $tr.length < 1) return;
                var editmodel = $tr.attr("data-editmodel");
                if (editmodel == undefined || editmodel == "display") return;
                $tr.attr("data-editmodel", 'display');
                $tr.find("td").each(function() {
                    var me = $(this);
                    var text = me.find("." + Ladder.form.Components.fetchMark).val();
                    me.html(text);
                });
            },
            setTitle: function(str) {
                $(this.settings.parentEL).find(".caption").html(str);
            },
            /**
             * 置编辑模式
             * @param $tr
             */
            setRowEdit: function($tr) {
                if ($tr.length == 0) return;
                if ($tr.attr("data-editmodel") == "edit" || $tr.attr("data-editmodel") == "insert") return;
                $tr.attr("data-editModel", "edit");
                var me = this;
                $tr.find("td[data-modelindex]").each(function() {
                    var $this = $(this);
                    var index = $this.attr("data-modelindex");
                    if (/^\d*$/.test(index)) {
                        var tc = me.getColumnModel(index);
                        me.createEditView($this, tc, $this.text());
                    }
                    //if (index.indexOf("ext_") > -1)return;
                });
                $tr.find(":input:first").focus();
            },
            /**
             * 创建编辑组件视图,置列编辑模式的单元格form组件
             * @param ctd 列对象
             * @param cm 列数据模型
             * @param value 值
             */
            createEditView: function(ctd, cm, value) {
                if (cm.editable) {
                    if (cm.list && cm.list.length > 0)cm.inputType = "combox";
                    var input = Ladder.form.Components.createEl(cm.inputType || cm.wname);
                    value = value ? value : ctd.text();
                    //处理样式
                    input.css({ height: '100%', width: '100%', border: "none", padding: 0, margin: 0 });
                    ctd.css({ padding: 0, margin: 0 });
                    for (var pn in cm) {
                        if (/(Function)/.test(Ladder.getType(cm[pn])))continue;
                        Ladder.form.handleEl(input, pn, cm[pn]);
                    }
                    ctd.html(input);
                    Ladder.form.parseEl(ctd);
                    input.val(value);
                }
            },
            /**
             * 设置表头标题行的高度
             * @param h
             */
            setTitleHeight: function(h) { if (this.datagrid) this.datagrid.find("th").css("height", h); },
            /***
             * 快速外部queryform查询方法，此方法用于自定义表单的查询接口
             * 此方法自动保存forms里的key,充分发挥继承关系
             * @param key
             * @param value
             * @param isrequestload
             */
            setConditionForm: function(key, value, isrequestload) {
                if (!this.condition)this.condition = {};
                if (!this.condition.forms)this.condition.forms = {};
                var forms = this.condition.forms;
                var type = Ladder.getType(key);
                if (type === "String") {
                    forms[key] = value;
                }
                if (type === "Object") {
                    $.extend(forms, key);
                }
                this.setCondition("forms", forms);
                if (isrequestload == undefined || isrequestload === true) {
                    this.loadRemote();
                }
            },
            /**
             * 设置查询条件
             * @param option 可以是属性值，也可以是对象
             * @param value 当option是对象，真和空为继承，false为直接取代
             */
            setCondition: function(option, value) {
                var me = this;
                if (Ladder.getType(option) === "String") {
                    if (value) {
                        var temp = new Object();
                        temp[option] = value;
                        option = temp;
                    } else {
                        if (me.condition && me.condition.hasOwnProperty(option)) {
                            delete me.condition[option];
                            me.settings.queryData.condition = JSON.stringify(me.condition);
                            return;
                        }
                    }
                }
                if (Ladder.getType(option) === "Object") {
                    if (!me.condition) {
                        me.condition = new Object();
                    }
                    //是否继承条件
                    if (value == undefined || value) {
                        $.extend(me.condition, option);
                    } else {
                        me.condition = option;
                    }
                    me.settings.queryData.condition = JSON.stringify(me.condition);
                }
            },
            /**
             * 请求数据，可默认全空
             * @param url
             * @param data
             */
            requestData: function(url, data) {
                var me = this;
                if (!url) url = me.settings.queryUrl; //路径置默认
                if (!data) { //条件数据为空
                    data = me.settings.queryData; //置默认
                    if (me.condition && Ladder.getType(me.condition) == "Object") { //自身的condition
                        //如果初始化参数中含有condition，进行继承
                        if (data.hasOwnProperty("condition")) {
                            data.condition = $.extend(Ladder.toJSON(data.condition), me.condition);
                        } else {
                            data.condition = me.condition;
                        }
                    }
                } else {
                    data = $.extend(me.settings.queryData, data);
                    if (data.hasOwnProperty("condition")) {
                        delete me.settings.queryData.condition;
                        if (Ladder.getType(data.condition) == "String")data.condition = Ladder.toJSON(data.condition); //我要对象型-->置换类型
                        //置换现行的condition
                        if (Ladder.getType(data.condition) == "Object") {
                            if (me.condition && Ladder.getType(me.condition) == "Object") {
                                me.condition = $.extend(me.condition, data.condition);
                                data.condition = me.condition;
                            } else {
                                me.condition = data.condition;
                            }
                        }
                    }
                }
                if(me.settings.onRequestBefore&&me.settings.onRequestBefore(data)===false)return;
                Ladder.progressBar(me.settings.parentEL);
                webajax(url, data, function(json) {
                    if (me.settings.onBefore) {
                        var re_t = me.settings.onBefore(json);
                        if (re_t !== undefined && re_t === false) {
                            Ladder.stopProgress();
                            return;
                        }
                    }
                    Ladder.stopProgress();
                    me.fillData(json);
                }, function() { Ladder.stopProgress(); }, 0);
            },
            /**
             * 查找列数据的索引，2015-7-23：现使用于合并字段的寻址
             * @param val
             * @param type
             * @returns {number}
             */
            findModelIndex: function(val, type) {
                var me = this;
                if (type == undefined) type = "fieldname";
                if (!me.columnModel || me.columnModel.length < 1) return -1;
                for (var i = 0; i < me.columnModel.length; i++) {
                    var _col = me.columnModel[i];
                    if (_col.hasOwnProperty(type) && _col[type] == val) {
                        return i;
                    }
                }
                return -1;
            },
            /**
             * 填充请求数据
             * @param json
             * @param type:0||undefined:ajaxjson,1,[Object]对象数据,2[[]]二维数组
             * @returns {*}
             */
            fillData: function(json, type) {
                var me = this;
                json = Ladder.toJSON(json);
                me.clear() //清空当前表体的数据
                if (type == undefined || type == 0) {
                    var reader = me.settings.reader;
                    var statusCode = reader.statusCode; //判断返回码，可以为空，如果不为空，则statuscode必须等于200
                    if (statusCode == undefined || (json.hasOwnProperty(reader.statusCode) && json[reader.statusCode] == 200)) {
                        if (reader.columnModel && me.option("autoColumnModel") == true) {
                            // 重新分配列配置
                            me.setColumnModel(Ladder.toJSON(eval("json." + reader.columnModel)));
                            //重写表头
                            me.rewriteHead();
                            //重新queryform，简单过滤条件
                            if (me.settings.queryFormEL && reader.queryform && !me.runstatus.B_queryFrom) {
                                var formdata = Ladder.toJSON(eval("json." + reader.queryform));
                                me.addQueryForm(formdata, me.settings.onQueryForm,me.settings.queryFormEL);
                                me.runstatus.B_queryFrom = true;
                            }
                        }
                        var griddata = null;

                        if (reader.data) griddata = Ladder.toJSON(eval("json." + reader.data));
                        if (!griddata) me.griddata = [];
                        me.griddata = griddata;
                        me.reloadData();
                        //处理分页,如果分页元素存在，且总页数大于1，显示分页界面
                        if (me.option("pageEL")) {
                            if (!me.condition) me.condition = new Object();
                            me.condition.pager = Ladder.toJSON(eval("json." + reader.pager));
                            me.setPager();
                        }
                        //数据加载完成后，判断是不是一体表格
                        if (me.settings.thType == 0 || me.settings.thType == 1) {
                            if (me.settings.sorter) {
                                //me.datagrid.tablesorter();
                            }
                            if (me.settings.resizable) {
                                //me.datagrid.resizableColumns();//此方法有bug,2015-7-23,
                                me.handColumnResize();
                            }
                        }
                        //处理其他外援数据
                        me.fullColumns = Ladder.toJSON(eval("json." + reader.fullcolumns));
                    } else {
                        //出现错误
                    }
                }
                if (type == 1) {
                    if (!json) return 400;
                    me.griddata = json;
                    me.reloadData();
                }

                //是否有跨行合并到字段设置
                var isspan = false;
                for (var i = 0; i < me.columnModel.length; i++) {
                    if (me.columnModel[i].spanrow) {
                        isspan = true;
                        me.spanRow(i);
                    }
                }
                if (isspan) {
                    me.settings.sorter = false;
                    me.runstatus.THObject.find("th").removeClass("head").off();
                }

                me.datagrid.find("tbody tr:first td").each(function() {
                    $(this).attr("width", $(this).width());
                });

                //加载更多分页
                if (me.settings.rollload) {
                    if (!me.condition) me.condition = new Object();
                    me.condition.pager = Ladder.toJSON(eval("json." + reader.pager));
                    if (me.condition.pager.pageCount > me.condition.pager.pageNumber) {
                        var $lasttr = me.datagrid.find("tbody tr:last");
                        var $mtr = $("<tr class='yui-datagrid-loadmore'></tr>");
                        $lasttr.after($mtr);
                        var $mtd = $("<td><div class='yui-datagrid-loadmore-hint'>加载更新数据</div></td>").attr("colspan", $lasttr.find("td").length).appendTo($mtr);
                        $mtr.click(function () {
                            me.loadMore();
                        });
                    }
                }

                //整理视图下沉的layoutH
                me.layoutSize(true);
                setTimeout(function() {
                    me.layoutSize(true);
                    if (me.settings.thType != 1)
                        me.fixTable();

                }, 500);
                //表格渲染完成事件
                if (me.settings.onFinished) {
                    me.settings.onFinished(me.griddata, me.datagrid);
                }
                $(me.settings.parentEL).find(".counterView .closeicon").trigger("click");


                return true;
            },
            /**
             * 加载更多数据
             * @returns {}
             */
            loadMore: function () {
                var me = this;
                if (!me.condition.pager) return;
                if (me.condition.pager.pageCount <= me.condition.pager.pageNumber) {
                    me.datagrid.find(".yui-datagrid-loadmore-hint").html("到底数据底部");
                    return;
                };
                var pageData = me.condition.pager;

                if (me.settings.onPaging) {
                    var re_t = me.settings.onPaging(pageData.pageNumber, pageData.pageSize, pageData);
                    if (re_t === false) {
                        return;
                    }
                }
                pageData.pageNumber++;
                var data = me.settings.queryData; //置默认
                if (me.condition && Ladder.getType(me.condition) == "Object") { //自身的condition
                    //如果初始化参数中含有condition，进行继承
                    if (data.hasOwnProperty("condition")) {
                        data.condition = $.extend(Ladder.toJSON(data.condition), me.condition);
                    } else {
                        data.condition = me.condition;
                    }
                }
                Ladder.progressBar(me.settings.parentEL);
                webajax(me.settings.queryUrl, data, function (json) {
                    if (me.settings.onBefore) {
                        var re_t = me.settings.onBefore(json);
                        if (re_t !== undefined && re_t === false) {
                            Ladder.stopProgress();
                            return;
                        }
                    }
                    var griddata = Ladder.toJSON(eval("json." + me.settings.reader.data));
                    if (!griddata) {
                        Ladder.stopProgress();
                        return;
                    }
                    me.griddata = griddata;
                    for (var x = 0; x < me.griddata.length; x++) {
                        me.addRow(me.griddata[x], false, me.datagrid.find(".yui-datagrid-loadmore").index());
                    }
                    //整理视图下沉的layoutH
                    me.layoutSize(true);
                    setTimeout(function () {
                        me.layoutSize(true);
                        if (me.settings.thType != 1)
                            me.fixTable();
                    }, 500);
                    setTimeout(function () {
                        Ladder.stopProgress();
                    }, 2000);
                    if(me.settings.onFinished)me.settings.onFinished();
                }, function () { Ladder.stopProgress(); }, 0);

            },


            /**
             * 处理界面下沉和扩展宽度
             * 2015-10-20 暂实现部分
             * @param ischeckData 是否检查数据高度
             * @param freeHead 是否冻结首行
             */
            layoutSize:function(ischeckData,freeHead){
                var me=this;
                var $el=$(me.settings.parentEL);
                //如果存在layoutH属性
                if(Ladder.getType(me.settings.layoutH)=="Number"&&$el.find(".yui-datagrid-body").length>0){
                    var _bottom=$el.offset().top+me.settings.height-me.settings.layoutH;//整个区域的底部纵点
                    var $datagridfoot=$el.find(".yui-datagrid-foot");
                    var $datagridbody=$el.find(".yui-datagrid-body");
                    $el.find(".yui-datagrid-space").height(0).empty();
                    var height = me.datagrid.height();
                    var hasHscrol = false;
                    $datagridbody.css("height", me.datagrid.height());
                    if (me.datagrid.width() > me.settings.width) {
                        hasHscrol = true;
                        height += 17;
                        $datagridbody.css("height", me.datagrid.height() + 17);
                    }
                    var _trueBottom = $datagridfoot.length > 0 ? $datagridfoot.offset().top + $datagridfoot.height() : $datagridbody.offset().top + height;
                    if(_bottom>_trueBottom){
                        $el.find(".yui-datagrid-space").height(_bottom - _trueBottom + (hasHscrol ? -17 : 0));
                        $datagridbody.css("height", me.datagrid.height() + _bottom - _trueBottom + (hasHscrol?17:0));
                        if(ischeckData&&(!me.griddata||me.griddata.length<1)) {
                            $el.find(".yui-datagrid-space").append("<div class='nodata'>对不起，暂无符合的数据显示！</div>");
//                        me.griddata.parent().css("overflow", "hidden");
                        }
                    }else{
                        $el.find(".yui-datagrid-space").height(0);
                        var _h = $datagridbody.height();
                        $datagridbody.height(_h - (_trueBottom - _bottom));
                    }
                }
            },
            /**
             * 重新表头,表格组件内部重要方法
             * 其数据来源于组件变量中的columnModel
             * @private
             */
            rewriteHead: function (isfill) {
                var me = this;
                var titletr = $("<tr></tr>");
                //首列选择框的处理
                if (me.settings.multiSelect) {//判断是否存在选择框功能
                    var $selectArea = $("<td></td>").html("全选").addClass("selectArea").attr("data-modelindex", "selectArea").attr("align","center");
                    if (me.settings.multiSelect == "only") {
                        $selectArea.html("选择");
                    } else {
                        $selectArea.on("click", function () {
                            var $this = $(this);
                            var ttext = $this.html();
                            var selects=null;
                            if(me.settings.freeze>0){
                                $selects=me.settings.parentEL.find(".yui-datagrid-body .yui-datagrid-body-columns>table>tbody>tr>td:nth-child(1) input.js-select");
                            }else{
                                $selects= me.datagrid.find("tbody tr td:nth-child(1) input.js-select");
                            }
                            switch (ttext) {
                                case "全选":
                                    if(me.settings.multiSelect==="keep"){
                                        $selects.prop("checked", true);
                                    }else{
                                        $selects.each(function () {
                                            var $e = $(this);
                                            $e.prop("checked", true);
                                            var gendata = me.fetchgendata($e.parents("tr"));
                                            if(gendata)me.multiSelectData[gendata] = true;
                                        });
                                    }
                                    $this.html("不选");
                                    if (me.settings.onCheck) me.settings.onCheck("all");
                                    break;
                                case "不选":
                                    if(me.settings.multiSelect==="keep") {
                                        $selects.prop("checked", false);
                                    }else{
                                        $selects.each(function () {
                                            var $e = $(this);
                                            $e.prop("checked", false);
                                            var gendata = me.fetchgendata($e.parents("tr"));
                                            if(gendata)delete me.multiSelectData[gendata];
                                        });
                                    }
                                    $this.html("全选");
                                    if (me.settings.onCheck) me.settings.onCheck("none");
                                    break;
                                case "反选":
                                    $selects.each(function () {
                                        var $me = $(this);
                                        var gendata=null;
                                        if(me.settings.multiSelect==="keep"){
                                            gendata = me.fetchgendata($me.parents("tr"));
                                        }
                                        if (!$me.prop("checked")) {
                                            $me.prop("checked", true);
                                            if(gendata)me.multiSelectData[gendata] = true;
                                        } else {
                                            $me.prop("checked", false);
                                            if(gendata)delete me.multiSelectData[gendata];
                                        }
                                    });
                                    if (me.settings.onCheck) me.settings.onCheck("not");
                                    break;
                                default:
                            }
                        });
                    }
                    titletr.append($selectArea);
                }
                //实体数据表头处理过程
                for (var i = 0; i < me.columnModel.length; i++) {
                    //列模型
                    var _col = me.getColumnModel(i);
                    //前置处理列模型
                    //1)处理列合并
                    if (_col.hasOwnProperty("join") && _col.join) {
                        var joinText = _col.join;
                        var _type = Ladder.getType(joinText);
                        switch (_type) {
                            case "String":
                            {
                                var _index = me.findModelIndex(joinText, "fieldname");
                                if (_index == -1) {
                                    _index = me.findModelIndex(joinText, "title");
                                }
                                if (_index > -1) {
                                    _col["joinindex"] = _index;
                                    me.columnModel[i] = _col;
                                }
                            }
                                break;
                            case "Number":
                                _col["joinindex"] = joinText;
                                me.columnModel[i] = _col;
                                break;
                            default:
                        }
                    }
                    if(_col.isshow===false||_col.join)continue;//合并列或者不显示
                    //列html代码
                    var $th = $("<th></th>").attr("data-modelindex", i).attr("data-fieldname", _col.fieldname).html(_col.title);
                    //是否是独立的视图
                    if(_col.subview){
                        if(titletr.find("td[data-subview='"+_col.subview+"']").length===0){
                            me.settings.sorter=false;
                            titletr.find("th").removeClass("header");
                            var subth=$("<td></td>").attr("data-subview",_col.subview).addClass("yui-datagrid-subColumn");
                            //调整显示顺序
                            if (_col.index == undefined || _col.index >= titletr.children().length) {
                                titletr.append(subth);
                            } else {
                                var $per = $(titletr.children().get(_col.index));
                                $per.before(subth);
                            }
                            if(!me.subview)me.subview={};
                            if(!me.subview[_col.subview])me.subview[_col.subview]="datagrid";
                            if(me.subview[_col.subview]==="datagrid"){
                                subth.append("<div class='yui-datagrid-subview'><table class='yui-datagrid-subgrid'><thead></thead></table></div>");
                                var _subtr=$("<tr></tr>").appendTo(subth.find("table.yui-datagrid-subgrid thead"));
                                _subtr.append($th);
                            }
                        }else{
                            if(me.subview[_col.subview]==="datagrid"){
                                var _subtr=titletr.find("td[data-subview='"+_col.subview+"'] table.yui-datagrid-subgrid thead tr");
                                _subtr.append($th);
                            }
                        }
                    }else{
                        //调整显示顺序
                        if (_col.index == undefined || _col.index >= titletr.children().length) {
                            titletr.append($th);
                        } else {
                            var $per = $(titletr.children().get(_col.index));
                            $per.before($th);
                        }
                    }
                    if (_col.width) {//置默认宽度
                        $th.css({ width: _col.width });
                    };
                    //是否是排序字段
                    if((_col.sort||_col.sort==undefined)&&me.settings.sorter){
                        $th.addClass("header");
                        $th.on("click",function(){
                            if(me.settings.sorter===false)return;
                            var $head=$(this);
                            var modelindex=$(this).attr("data-modelindex")*1;
                            var thconfig = me.getColumnModel(modelindex);
                            if(thconfig&&thconfig.sort===false)return;
                            var $allth=$head.siblings();
                            if($allth.hasClass("headerSortDown"))$allth.removeClass("headerSortDown");
                            if($allth.hasClass("headerSortUp"))$allth.removeClass("headerSortUp");
                            if($head.hasClass("headerSortDown")){
                                if(Ladder.getType(thconfig.sort)=="Function"){
                                    thconfig.sort(thconfig,0);
                                }else{
                                    if(Ladder.getType(me.settings.sorter)=="Function"){
                                        me.settings.sorter(thconfig,0);
                                    }else{
                                        me.handsort($head.index()+1,0);
                                    }
                                }
                                $head.removeClass("headerSortDown");
                                $head.addClass("headerSortUp");
                            }else{
                                if(Ladder.getType(thconfig.sort)=="Function"){
                                    thconfig.sort(thconfig,1);
                                }else{
                                    if(Ladder.getType(me.settings.sorter)=="Function"){
                                        me.settings.sorter(thconfig,1);
                                    }else{
                                        me.handsort($head.index()+1,1);
                                    }
                                }
                                $head.removeClass("headerSortUp");
                                $head.addClass("headerSortDown");
                            }
                        });
                    }
                }
                if(me.extColumnModel&&me.extColumnModel.length){
                    for(var i=0;i<me.extColumnModel.length;i++){
                        var ext_c=me.extColumnModel[i];
                        if(ext_c.isshow == undefined || ext_c.isshow){
                            var $th = $("<th></th>").attr("data-modelindex","ext_"+i).html(ext_c.title);
                            if (ext_c.width) {
                                $th.css({ width: ext_c.width });
                            };
                            if(ext_c.display!=undefined){
                                $th.css("display",ext_c.display);
                            }
                            if(ext_c.mark!=undefined)$th.attr("data-mask",ext_c.mark);
                            if (ext_c.index == undefined || ext_c.index >= titletr.children().length) {
                                titletr.append($th);
                            } else {
                                var $percol = $(titletr.children().get(ext_c.index * 1));
                                if ($percol.length > 0) $percol.before($th);
                            }
                            if(ext_c.colspan!=undefined){
                                if(ext_c.colspan>1){
                                    $th.attr("colspan",ext_c.colspan);
                                }else{
                                    $th.remove();
                                }
                            }
                        }
                    }
                }
                //冻结首行和自动分配首行
                me.runstatus.THObject = titletr;//存储到运行状态参数中
                if(isfill===false)return;
                me.datagrid.find("thead").html(titletr);
//            me.settings.thType=1;

            },
            /**
             *
             * @param data 数据
             * @param callback 回调函数
             * @param el 父级元素
             */
            addQueryForm:function(data,callback,el){
                var me = this;
                var tul = null;
                if (el == undefined) el = me.settings.queryFormEL;
                el = $(el);
                if (el.length < 1) return;
                if ((el[0].nodeName).toLowerCase() == "ul") tul = el;
                if (!tul) tul = el.find("ul");
                if (tul.length < 1) return;
                var oldformsize=tul.find("li").length;
                var forms=[];
                var type=Ladder.getType(data).toLocaleLowerCase();
                switch (type){
                    case "string":
                        forms.push({formname:data,title:data});
                        break;
                    case "object":
                        if(data.hasOwnProperty("list")&&Ladder.getType(data.list)=="Array"){
                            forms=data.list;
                        }else{
                            forms.push(data);
                        }
                        break;
                    case "array":
                        forms=data
                        break;
                }
                if (forms.length<1) return;
                // tul.empty();
                for (var i = 0; i < forms.length; i++) {
                    var $li = $("<li></li>");
                    var form = forms[i];
                    if(!form)continue;
                    var titleel = '<span class="querytitle">' + form.title + '</span>';
                    $li.append(titleel);
                    //var input = Ladder.form.Components.createEl(form.inputType);
                    if(form.inputType)form.wname=form.inputType;
                    var input = Ladder.Form.createForm(form);
                    delete form.inputType;
                    delete form.title;
                    for (var name in form) input.attr("data-" + name, form[name]);
                    $li.append(input);
                    Ladder.form.parseEl($li);
                    tul.append($li);
                }
                //填充查询按钮
                if (tul.find("li").length > 0) {
                    if (me.settings.queryFormAction.indexOf("button") > -1) {
                        var button = $("<button style='margin-left: 5px;' class='js-query'>搜索查询</button>");
                        if(tul.parent().find(".js-query").length<1){
                            tul.after(button);
                            if(callback || !oldformsize)button.click(function () {me.querybyForm(tul,callback);});
                        }
                    }
                    if (me.settings.queryFormAction.indexOf("auto") > -1&&(callback || !oldformsize)) {//判断queryform的查询方式
                        $(tul).find("." + Ladder.form.Components.fetchMark + "[data-rw=1]").on("change", function () {
                            me.querybyForm(tul, callback);
                        }).on("keydown", function (e) {
                            var theEvent = e || window.event;
                            var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
                            if (code == 13) me.querybyForm(tul, callback);
                        });
                    }
                }
                if(me.settings.onFormRender)me.settings.onFormRender(tul,forms);
            },
            /**
             * 组装QueryForm组件
             * @private
             * @param el 父级元素
             * @param formdata 组装的数据
             * @param fun 回调函数(查询前)
             */
            diyQueryForm: function (el, formdata, fun) {
                this.addQueryForm(formdata,fun,el);
                return;
            },
            /**
             * 内部方法,通过表单上级组件进行forms封装
             * @private
             * @param {} formParentEl
             * @param {} fun
             * @returns {}
             */
            querybyForm: function (formParentEl, fun) {
                var me = this;
                var formquerydata = Ladder.form.fetchFormValue(formParentEl, "data-formname", false,null,"data-dvalue");
                if(formquerydata){
                    for(var n in formquerydata){
                        if(!formquerydata[n])formquerydata[n]=null;
                    }
                }
                if (fun) {
                    var re_t=fun(formquerydata,me.condition);
                    if(re_t!=undefined&&!re_t)return;
                }
                if (me.settings.queryUrl) {
                    if (!me.condition)  me.condition = new Object();
                    if (me.condition.forms) {
                        me.condition.forms = Ladder.toJSON(me.condition.forms);
                        formquerydata=$.extend(me.condition.forms,formquerydata);
                    }
                    me.condition.forms = JSON.stringify(formquerydata);
                    me.condition.pager = undefined;
                    //me.condtion.forms="[{fieldname:'title',op:'like',value:'%java%'}]";
                    me.requestData();
                }
            },
            /**
             * 内部方法->处理分页
             * @private
             * @param {} el
             * @param {} pageData
             * @param {} fun
             * @returns {}
             */
            setPager: function (pageData,el) {
                var me=this;
                var pageEL = null;
                if (el == undefined)  pageEL = $(me.settings.pageEL);
                else  pageEL = $(el);
                if(pageEL.length<1)return;
                if (pageData == undefined) pageData = me.condition ? me.condition.pager : null;
                else {
                    if(!me.condition)me.condition={};
                    me.condition.pager=pageData;
                }
                if (!pageData) return;
                //填写一些页数据到页面
                Ladder.form.setSelectValue(pageEL.find(".pagesize"), pageData.pageSize);
                pageEL.find(".total").html(pageData.recordCount);
                pageEL.find(".js-gopage").val(pageData.pageNumber);
                pageEL.find(".js-end").attr("data-page", pageData.pageCount);
                pageEL.find(".js-next").attr("data-page", pageData.pageNumber < pageData.pageCount ? pageData.pageNumber + 1 : pageData.pageCount);
                pageEL.find(".js-previous").attr("data-page", pageData.pageNumber > 1 ? pageData.pageNumber - 1 : 1);
                pageEL.find(".pagecount").html("页,共"+pageData.pageCount+"页 ");
            },
            /**
             * 加载远端数据，组件外部重要方法
             * @param url 可空，默认为setting.queryURL
             * @param querydata
             */
            loadRemote: function (url,querydata) {
                this.requestData(url,querydata);
            },
            /**
             * 设置列模型
             * @param {} model
             * @returns {}
             */
            setColumnModel: function (model) {
                if (Ladder.getType(model) == "Array") {
                    this.columnModel = new Array();
                    for (var i = 0; i < model.length; i++) {
                        var obj_model = model[i];
                        if (obj_model.hasOwnProperty("fieldname")) {
                            var fieldname = obj_model["fieldname"];
                            var fileds = fieldname.split(".");
                            obj_model["fieldname"] = fileds[fileds.length - 1];
                        }
                        var tc = this.getColumnModel(i);
                        this.columnModel[i] = $.extend(tc, obj_model);
                        if(this.columnModel[i].isshow===0&&this.columnModel[i].gen)this.columnModel[i].isshow=false;
                        if(!(this.columnModel[i].isshow===false))this.columnModel[i].isshow=true;
                        if (this.columnModel[i].list && Ladder.getType(this.columnModel[i].list) === "String" && (!this.columnModel[i].dataList)) {
                            var ls = this.columnModel[i].list.split("|");
                            var dataList = {};
                            for (var t = 0, len = ls.length; t < len; t++) {
                                var d = ls[t].split(":");
                                if (d.length > 1) dataList[d[1] + ""] = d[0];
                            }
                            this.columnModel[i]["dataList"] = dataList;
                        }
                    }
                }
                //备留接口
                if (Ladder.getType(model) == "Object") {
                    this.addColumn(model);
                }
            },
            /**
             * 添加字段列
             * @param index 位置
             * @param isreplace 是否相同替换
             */
            addColumn:function(model,index,isreplace){
                if(model==undefined)return;
                var _type=Ladder.getType(model);
                var _col=this.getColumnConfigTemplate();
                switch (_type){
                    case "String":_col.title=model;break;
                    case "Array":
                        for(var i= 0;i<model.length;i++)this.addColumn(model[i],index,isreplace);return;
                    case "Object":
                        $.extend(_col,model);
                        if (_col.list && !_col.dataList && Ladder.getType(_col.list) === "String") {
                            var ls = _col.list.split("|");
                            var dataList = {};
                            for (var t = 0, len = ls.length; t < len; t++) {
                                var d = ls[t].split(":");
                                if (d.length > 1) dataList[d[1] + ""] = d[0];
                            }
                            _col["dataList"] = dataList;
                        }
                        break;
                    default :return;
                }
                if(index==undefined)index=this.columnModel.length;
                if(!isreplace){
                    this.columnModel.splice(index,0,_col)
                }else{
                    this.columnModel=this.columnModel.filter(function(item){
                        if(_col.title.length>0&&_col.title==item.title)return true;
                        if(_col.fieldname.length>0&&_col.fieldname==item.fieldname)return true;
                        return false;
                    });
                    this.columnModel.splice(index,0,_col);
                }
                if(!this.settings.autoColumnModel)this.rewriteHead();
            },

            /**
             * 外部重要方法
             * index尽量使用fieldname或者序号
             * 使用方法可以是:dg.setColumnConfig("total,htotal,braid", {width: "16%"});
             *
             * 2015-12-30:新增属性:spanrow->合并行，counter:统计
             * @param {String/Number/Object} index
             * @param {} obj
             * @returns {}
             */
            setColumnConfig: function (index, obj) {
                if(Ladder.getType(obj)=="Function")obj={callback:obj};
                if(Ladder.getType(obj)=="Boolean")obj={isshow:obj};
                var _t=Ladder.getType(index);
                if (_t== "Number")  this.columnModel[index] = $.extend(this.getColumnModel(index), obj);
                if (_t== "String") {
                    var fields=index.split(/,|\|/);
                    for(var i=0;i<fields.length;i++){
                        if (this.columnFilter.hasOwnProperty(fields[i])) {
                            this.columnFilter[fields[i]] = $.extend(this.columnFilter[fields[i]], obj);
                        } else {
                            this.columnFilter[fields[i]] = $.extend({},obj);
                        }
                    }
                }
                if(_t=="Object"&&arguments.length==1){
                    for(var propName in index){
                        this.setColumnConfig(propName,index[propName]);
                    }
                }
            },
            /**
             * 获取column模型的模版,公版以及测试使用
             */
            getColumnConfigTemplate:function(){
                return {
                    fieldname: '',
                    title: '',
                    editable: true,
                    inputType: "linetext",
                    valid: null,
                    isshow: true,
                    sort:true,
                    align: this.settings.columnAlign ? this.settings.columnAlign : 'left',
                    valign: this.settings.columnVAlign ? this.settings.columnVAlign : 'middle',
                    colspan:1
                };
            },
            /**
             * 获取列模型，内部重要方法
             * @param {} index
             * @returns {}
             */
            /**
             * 获取一个列模型,内部使用，外部无用
             * @param {} index
             * @returns {}
             */
            getColumnModel: function (index) {
                if (index >= 0) {
                    if (!this.columnModel[index]) this.columnModel[index] = this.getColumnConfigTemplate();
                    var cc = this.columnModel[index];
                    if (cc["title"] && this.columnFilter[cc["title"]]) {
                        cc = $.extend(cc, this.columnFilter[cc["title"]]);
                    }
                    if (cc["fieldname"] && this.columnFilter[cc["fieldname"]]) {
                        cc = $.extend(cc, this.columnFilter[cc["fieldname"]]);
                    }
                    return cc;
                }
                return undefined;
            },
            /**
             *增加扩展列
             * @param columnModel {String/Object} 列模型，如果是String直接为列的HTML代码
             */
            addExtColumn:function(columnModel){
                if(columnModel==undefined || columnModel==null)return -1;
                var me=this;
                if(!me.extColumnModel)me.extColumnModel=new Array();
                var dataType=Ladder.getType(columnModel);
                if(dataType=="String"){
                    me.extColumnModel.push({
                        showText:columnModel
                    });
                }
                if(dataType=="Object"){
                    me.extColumnModel.push(columnModel);
                }
                return me.extColumnModel.length-1;
            },
            /**
             *删除扩展列
             * @param ｛number｝列序号
             */
            deleteExtColumn:function(index){
                var me=this;
                if(!me.extColumnModel)return;
                me.extColumnModel.remove(index);
            },
            /**
             * 设置表格扩展列的属性
             * @param index 序号
             * @param columnModel 列模型 如果是String直接替换为列的HTML代码
             * @returns {*}
             */
            setExtColumnConfig:function(index,columnModel){
                if(columnModel==undefined || columnModel==null)return -1;
                var me=this;
                if(!me.extColumnModel)return false;
                var config=me.extColumnModel[index];
                var dataType=Ladder.getType(columnModel);
                if(dataType=="String"){
                    config.showText=columnModel;
                }
                if(dataType=="Object"){
                    config= $.extend(config,columnModel);
                }
                me.extColumnModel[index]=config;
                return true;
            },
            /**
             *
             */
            setCurrentRow:function(tr){
                var $tr=$(tr);
                if($tr.length<1)return;
                $tr.addClass("currentSelect").siblings().removeClass("currentSelect");
                this.selectRow=$tr;
            },
            /**
             * 添加一行数据到表格
             * @param rowData 可为null array string object
             * @param editable 编辑模式
             * @param direction 默认是从倒序，如果是number为指定行号追加
             * @returns {boolean}
             */
            addRow: function (rowData, editable, direction) {
                var me = this;
                var datagrid = me.datagrid;
                var tr = $("<tr></tr>");
                var subtrs={};
                tr.click(function () {//单击事件，变更选区的颜色
                    if(me.settings.onRowLeave&&me.selectRow&&me.selectRow.index()!=$(this).index())
                        me.settings.onRowLeave(me.selectRow,$(this));
                    if (me.selectRow)
                        me.selectRow.removeClass(me.option("selectClass"));
                    me.selectRow = $(this);
                    me.selectRow.addClass(me.option("selectClass"));
                    if(me.settings.onSelectRow)me.settings.onSelectRow(me.selectRow,rowData);
                });
                //注册双击事件
                if(me.settings.onDblClick) {
                    tr.on("dblclick", function () {
                        me.settings.onDblClick($(this),rowData);
                    });
                }
                if (Ladder.getType(rowData) == "String") rowData = Ladder.toJSON(rowData);//转换String数据
                tr.data("rowData", rowData);//把数据追加到元素的存储区
                if (editable) tr.attr("data-editmodel", "insert");//如果是编辑模式，做标记
                //以表头最底的行作为基础，进行列前期创建
                if (!me.runstatus.THObject) return false;
                //创建td，并指定modelindex
                me.runstatus.THObject.children().each(function () {
                    //含有子视图的情况
                    if($(this).attr("data-subview")){
                        var subviewName=$(this).attr("data-subview");
                        subtrs[subviewName]=$("<tr></tr>");
                        var subtd = datagrid.find("tbody:first td[data-subview='"+subviewName+"']");
                        if(subtd.length<1){
                            subtd=$("<td data-subview='" +subviewName + "' class='yui-datagrid-subdata'><div><table><tbody></tbody></table></div></td>");
                            tr.append(subtd);
                            $(this).find(".yui-datagrid-subgrid th[data-modelindex]").each(function(){
                                subtrs[subviewName].append("<td data-modelindex='" + $(this).attr("data-modelindex") + "'></td>");
                            });
                            subtd.find("table tbody").append(subtrs[subviewName]);
                        }else{
                            $(this).find(".yui-datagrid-subgrid th[data-modelindex]").each(function(){
                                subtrs[subviewName].append("<td data-modelindex='" + $(this).attr("data-modelindex") + "'></td>");
                            });
                            subtd.prop("rowspan",subtd.prop("rowspan")+1);
                        }
                        //$(this).prop("rowspan",$(this).prop("rowspan")+1);
                    }else{
                        tr.append("<td data-modelindex='" + $(this).attr("data-modelindex") + "'></td>");
                    }

                });
                var $tds = tr.find("td");//所有TD的集合,在下面的使用时，能缩小搜索范围
                for(var subName in subtrs){
                    $tds = $tds.add(subtrs[subName].find("td"));
                }
                if (me.settings.multiSelect) {
                    var $td = $tds.first();//选择框列组件
                    var $cb = $("<input type='checkbox' class='yui-datagrid-checkbox js-select'>");//checkbox选择框列组件
                    $td.append($cb).attr("align","center");
                    $cb.on("click", { "me": me }, me.multiCheck);//选择的内部事件
                }
                //添加实体数据
                me.columnModel.forEach(function(_col,i){
                    //for (var i = 0; i < me.columnModel.length; i++) {
                    //    var _col = me.getColumnModel(i);//列配置项模型
                    var cvalue = "";//列数据
                    if (rowData && Ladder.getType(rowData) == "Object") cvalue = rowData[_col.fieldname];
                    if (rowData && Ladder.getType(rowData) == "Array") cvalue = rowData[i];
                    //列的前提条件，并过滤uuid和id,auto_*三种,公用gen的后台模版，2015-11-23 兼容代码
                    if ((_col.gen && _col.fieldname && /(uuid)|(id)|(auto)/i.test(_col.gen))||_col.pk) {
                        var gens = tr.attr("data-gens") ? tr.attr("data-gens") + "|" + _col.fieldname : _col.fieldname;
                        tr.attr("data-gens", gens);
                        tr.attr("data-" + _col.fieldname + "-type", _col.gen);
                        tr.attr("data-" + _col.fieldname + "-value", cvalue);
                        //判断选框的存储值，应用于翻页
                        if (me.settings.multiSelect && me.multiSelectData.hasOwnProperty(cvalue)) {
                            $tds.first().find("input[type='checkbox']").prop("checked", true);
                        }
                    }
                    if (_col.subview) {
                        var subview = me.runstatus.THObject.find("th[data-subview='" + _col.subview + "']");
                    }
                    //是否显示该字段
                    if ((_col.isshow == undefined || _col.isshow)) {
                        //是否有强制显示文本
                        var dv=_col.showText||_col.value;
                        if (dv != undefined && dv.length > 0) {
                            cvalue = dv
                        } else {
                            //处理默认值，采用柔和方案，即无值替换
                            if (cvalue == undefined || cvalue.length == 0) cvalue = _col["defaultValue"];
                            //处理日期时间数据
                            if (_col.type && /date/i.test(_col.type)) {
                                //编辑模式,日期时间默认填充
                                if (editable) {
                                    cvalue = Ladder.dateFormat(cvalue, _col.format);
                                } else {//非编辑模式，hava value to fill
                                    if (cvalue) {
                                        if (!_col.hasOwnProperty("format")){ //如果不存在format
                                            var _format="";
                                            switch (_col.type.toLowerCase()){
                                                case "date":
                                                    _format="yyyy-MM-dd";
                                                    break;
                                                case "datetime":
                                                    _format="yyyy-MM-dd hh:mm:ss";
                                                    break;
                                            }
                                            // if (/0*:0*:0*(\.0)?$/.test(cvalue)) cvalue = Ladder.dateFormat(cvalue,_format);
                                            // else
                                            cvalue = Ladder.dateFormat(cvalue,_format);
                                        } else {
                                            cvalue = Ladder.dateFormat(cvalue, _col.format);//如果存在format
                                        }
                                    }
                                }
                            }
                        }
                        //正则替换
                        if (cvalue && _col.replaceRegEx) {
                            var type = Ladder.getType(_col.replaceRegEx);
                            if (type == "Array" && _col.replaceRegEx.length > 0) {
                                //正则以偶数一组替换,如果偶数不足，替换文本以空默认
                                var n = 0;
                                var max = _col.replaceRegEx.length;
                                while (n < max) {
                                    var regText = _col.replaceRegEx[n];
                                    var regValue = n + 1 < max ? _col.replaceRegEx[n + 1] : "";
                                    cvalue.replace(regText, regValue);
                                    n += 2;
                                }
                            }
                            if (type == "String") {//文本默认替换成空
                                cvalue.replace(_col.replaceRegEx, "");
                            }
                        }
                        //公式和计算,2015-6-20 datagrid暂时用处不大
                        //匹配联想字段
                        if (_col.dataList && Ladder.getType(_col.dataList) == "Object") {
                            if (_col.dataList.hasOwnProperty(cvalue)) cvalue = _col.dataList[cvalue];
                        }
                        //###2015-7-23 此处可性能优化：$tds 转化成对照表，此后不再使用find或者filter
                        if (cvalue == undefined) cvalue = '';
                        if (_col.hasOwnProperty("join") && _col.join) {//是合并字段
                            var fgf = _col.joinMask ? _col.joinMask : " ";//分割符
                            var ctd = $tds.filter("[data-modelindex='" + _col["joinindex"] + "']");
                            if (ctd.length > 0) {
                                var oldval = ctd.html() + fgf + cvalue;
                                ctd.html(oldval);
                                if (_col.hasOwnProperty("callback")) {//如果存在回调函数->2015-7-28
                                    var re = _col.callback(ctd, oldval, rowData, _col);//列元素,当前值，行数据，列模型
                                    if (re && re != oldval) ctd.html(re);
                                }
                            }
                        } else {//独立字段,获取列序对应的列，进行填
                            //var ctd = tr.find("td[data-modelindex='" + i + "']");
                            var ctd = $tds.filter("[data-modelindex='" + i + "']");
                            var oldval = cvalue + ctd.html();
                            ctd.html(oldval);
                            //截短
                            if((me.settings.words||_col.words)&&(_col.words==undefined||_col.words>0)){
                                var _len=_col.words||me.settings.words;
                                if(_len<oldval.length){
                                    ctd.html(oldval.substr(0,_len)+"…");
                                    ctd.attr("data-content",oldval);
                                    ctd.hover(function(){
                                        var $this=$(this);
                                        var showtext = $(this).attr("data-content");
                                        var $hit=$("<div class='yui-datagrid-contenthint'></div>");
                                        $hit.append("<span>"+showtext+"</span>");
                                        if(_col.width)$hit.width(_col.width-8);
                                        $hit.appendTo(ctd);
                                        $hit.offset($this.offset());
                                    },function(){
                                        ctd.find(".yui-datagrid-contenthint").remove();
                                        //    .fadeOut(800,function(){
                                        //    $(this).remove();
                                        //});
                                    });
                                }
                            }

                            if(me.runstatus.TableModel=="datagrid"){
                                ctd.attr("align", _col['align']);
                                ctd.attr("valign", _col['valign']);
                            }
                            //if(_col['width']!=undefined){
                            //    ctd.attr("width", _col['width']);
                            //}



                            if (_col.hasOwnProperty("callback")) {//如果存在回调函数->2015-7-28
                                var rez = _col.callback(ctd, oldval, rowData, _col);//列元素,当前值，行数据，列模型
                                if (rez && rez != oldval) {
                                    ctd.empty();
                                    ctd.append(rez);
                                }
                            }
                            ////是否含有标注
                            //if(rowData && Ladder.getType(rowData) == "Object"&& rowData.marker){
                            //    ctd.addClass("marker");
                            //}


                            //如果是新增的编辑模式
                            if (editable && _col.editable != false) {
                                me.createEditView(ctd, _col);
                            }
                        }

                    }
                    //}
                });

                //添加扩展数据
                if(me.extColumnModel&&me.extColumnModel.length&&(!editable)){
                    for(var i=0;i<me.extColumnModel.length;i++){
                        var _col=me.extColumnModel[i];
                        //是否显示该扩展字段
                        if (_col.isshow===false)continue;
                        var ctd;//扩展的列元素
                        if(_col.colspan!=undefined&&_col.colspan<1&&_col.colindex!=undefined){
                            ctd=$("<td data-modelindex='ext_" + i + "'></td>");
                            var pertd=$tds.filter("[data-modelindex='ext_" + _col.colindex + "']");
                            if(pertd.length>0){
                                pertd.after(ctd);
                            }
                        }else{
                            ctd = $tds.filter("[data-modelindex='ext_" + i + "']");
                        }
                        if(_col.display!=undefined){
                            ctd.css("display",_col.display);
                        }
                        if(_col.mark!=undefined){
                            ctd.attr("data-mask",_col.mark);
                        }
                        var cvalue = _col.showText || _col.defaultValue;
                        ctd.html(cvalue);
                        ctd.attr("align", me.settings.columnAlign);
                        ctd.attr("valign", me.settings.columnVAlign);
                        if(_col.width!=undefined)ctd.css("width",_col.width);
                        if (_col['align']) ctd.attr("align", _col['align']);
                        if (_col['valign']) ctd.attr("valign", _col['valign']);
                        if (_col.hasOwnProperty("callback")) {//如果存在回调函数->2015-7-28
                            var rez = _col.callback(ctd, cvalue, rowData, _col);//列元素,当前值，行数据，列模型
                            if (rez && rez != cvalue) {
                                ctd.empty();
                                ctd.append(rez);
                            }
                        }
                    }
                }
                //控制方向
                //如果是false，undefined，0时候在首行插入
                if (direction == undefined)  direction=0;//默认前插
                if(direction instanceof $)direction = direction.index();//行对象以行序
                if(Ladder.getType(direction)!="Number"){//逻辑型或者对象
                    if(direction)direction=0;
                    else direction=-1;
                }
                switch (direction){
                    case 0:
                        datagrid.find("tbody:first").prepend(tr);
                        for(var subname in subtrs){
                            var subtd = datagrid.find("tbody:first td[data-subview='"+subname+"'] table tbody");
                            subtd.prepend(subtrs[subname]);
                        }
                        break;
                    case -1:
                        datagrid.find("tbody:first").append(tr);
                        for(var subname in subtrs){
                            var subtd = datagrid.find("tbody:first td[data-subview='"+subname+"'] table tbody");
                            subtd.append(subtrs[subname]);
                        }
                        break;
                    default :
                        var cRow= datagrid.find("tbody:first tr:eq("+direction+")");
                        if(cRow.length<1){
                            datagrid.find("tbody:first").append(tr);
                            for(var subname in subtrs){
                                var subtd = datagrid.find("tbody:first td[data-subview='"+subname+"'] table tbody");
                                subtd.append(subtrs[subname]);
                            }
                            break;
                        }
                        cRow.before(tr);
                        for(var subname in subtrs){
                            var subtd = datagrid.find("tbody:first td[data-subview='"+subname+"'] table tbody tr:eq("+direction+")");
                            subtd.before(subtrs[subname]);
                        }
                }
                //是否有子数据
                if(rowData&&Ladder.getType(rowData)=="Object"&&rowData.children){
                    var cdatatype=Ladder.getType(rowData.children);
                    switch (cdatatype){
                        case "Function":
                            rowData.children(tr);
                            break;
                        case "Object":
                            var ctr = me.addRow(rowData.children,editable,tr.index());
                            tr.children(":first").addClass("parentNode_Noexpan");
                            ctr.hide().addClass("childNode_Noexpan");
                            break;
                        case "Array":
                            var uuid=tr.index()+Ladder.uuid(12,16);
                            tr.children(":first").attr("data-childuuid",uuid).addClass("parentNode_Noexpan").click(function(){
                                var $parent=$(this);
                                $parent.toggleClass("parentNode_expan");
                                $(this).parent().nextAll("[data-childuuid="+$(this).attr("data-childuuid")+"]").each(function(){
                                    $(this).toggle("1500");
                                });
                            });
                            for(var i=0;i<rowData.children.length;i++){
                                var ctr = me.addRow(rowData.children[i],editable,tr.index()+1);
                                ctr.hide().attr("data-childuuid",uuid).addClass("childNode_Noexpan");
                            }
                            break;
                        default:
                            break;
                    }
                }

                //智能滚动
                var $gridparent = datagrid.parent();
                if ($gridparent.hasClass("yui-datagrid-body") && me.settings.bodyHeight) {
                    var maxheight = me.settings.bodyHeight.toString().replace(/px/i, '')*1;
                    if (datagrid.height() > maxheight) {
                        $gridparent.css("overflow-y", "auto");
                        $gridparent.height(maxheight);
                    } else {
                        datagrid.parent().css("overflow-y", "hidden");
                        datagrid.parent().height(datagrid.height());
                    }
                }
                return tr;
            },
            /**
             * 替换一行,主要用于修改数据时，以及外部使用
             * @param {} $tr
             * @param {} rowData
             * @returns {}
             */
            replaceRow: function ($tr, rowData) {
                var me = this;
                if($tr&&!rowData){
                    if($tr instanceof $ || Ladder.getType($tr)!="Object")return;
                    if(!me.selectRow)return;
                    var index=me.selectRow.index();
                    me.selectRow.remove();
                    return me.addRow($tr, false,index);
                }
                if (!$tr || $tr.length < 1) return;
                var index=$tr.index();
                $tr.remove();
                return me.addRow(rowData, false,index);
            },
            //外部使用，内部无用
            getColumnSize: function () {
                var i = 0;
                if ((i = this.datagrid.find("tr:eq(0) th").length) > 0) return i;
                if ((i = this.datagrid.find("tr:eq(0) th").length) > 0) return i;
                return i;
            },
            getRowCount:function(){
                return this.datagrid.find("tbody tr").length;
            },
            /***
             * 获取表格上数据
             * @param type HtmlData/RowData,默认false->RowData,true->HtmlData
             * @param tr 行集合
             * @param visible 选择可视的数据
             */
            getGridData:function(type,tr,visible){
                var me=this;
                if(Ladder.getType(type)=="Function"){
                    var data=[];
                    me.datagrid.find("tbody tr").each(function(){
                        var $this=$(this);
                        var dat=$this.data("rowData");
                        var ret= type(dat,me.getRowData($this,true));
                        if(!(ret===false)){
                            if(ret)data.push(ret);
                            else data.push(dat);
                        }
                    });
                }else{
                    var $tr = undefined;
                    visible=((visible==undefined||visible)?":visible":"");
                    if(tr)$tr=$(tr);
                    else $tr = me.datagrid.find("tbody tr"+visible);
                    if($tr.length<1)return undefined;
                    var data=[];
                    $tr.each(function(){
                        if(!type){
                            data.push($(this).data("rowData"));
                        }else{
                            var re_t={};
                            $(this).find("td").each(function(){
                                var $this=$(this);
                                var mi=$this.attr("data-modelindex");
                                if(!/^\d*$/.test(mi))return;
                                var cm=me.getColumnModel(mi);
                                if($this.find(".js-yui").length>0){
                                    re_t[cm.fieldname]=$this.find(".js-yui").val();
                                }else re_t[cm.fieldname]=$this.text();
                            });
                            data.push(re_t);
                        }
                    });
                    return data;
                }
            },
            /**
             * 获取行数据，默认为当前行
             * 外部使用，内部无用
             * @param index,行号从0开始,也可以tr对象，默认当前选行
             * @param HtmlData/RowData,默认false->RowData,true->HtmlData
             * @return {*}
             */
            getRowData: function (index,type) {
                var me = this;
                var $tr;
                if (Ladder.getType(index) == "Number") {
                    $tr=me.datagrid.find("tbody tr:eq(" + index + ")");
                    if($tr.length<1)return null;
                    if(!type)return $tr.data("rowData");
                }else{
                    if(index==undefined){
                        if (!me.selectRow) return null;
                        if(!type||!index)return me.selectRow.data("rowData");
                        $tr=me.selectRow;
                    }else{
                        $tr=$(index);
                        if(!type)return $tr.data("rowData");
                    }
                }
                var re_t={};
                $tr.find("td").each(function(){
                    var $this=$(this);
                    var mi=$this.attr("data-modelindex");
                    if(!/^\d*$/.test(mi))return;
                    var cm=me.getColumnModel(mi);
                    re_t[cm.fieldname]=$this.text();
                });
                return re_t;
            },
            /**
             * 获取列的输入类型
             * @param index
             * @return {*}
             */
            getColumnType: function (index) {
                var tc = this.getColumnModel(index);
                if (tc.editable == false) return false;
                if (tc.inputType == undefined) return "linetext";
                return tc.inputType;
            },
            /**
             * 获取行的前置条件，方法和fetchgendata有重叠,根据用途进行区分->2015-7-26
             * @param $tr
             * @return {Array}
             */
            getRowFormers: function ($tr) {
                if ($tr == undefined) $tr = this.selectRow;
                else $tr=$($tr);
                if ($tr.data("editmodel") == "insert") return;
                var gens = $tr.attr("data-gens");
                var genarray = gens.split("|");
                var forms = new Array();
                for (var i = 0; i < genarray.length; i++) {
                    var _former = {
                        value: $tr.attr("data-" + genarray[i] + "-value"),
                        type: $tr.attr("data-" + genarray[i] + "-type"),
                        fieldname: genarray[i],
                        name: genarray[i],
                        op: "="
                    };
                    if(_former.value!=undefined)
                        forms.push(_former);
                }
                if(forms.length<1)return;
                return forms;
            },
            /**
             * 获取未保存的数据
             * 如果列模型中含有defaultValue时，将进行内容封装
             * @return {boolean/Array}
             */
            getNosavadata: function () {
                if (this.datagrid.find("." + Ladder.form.Components.fetchMark + "[data-rw=1]").length < 1) return;
                var nsave = new Array();
                var me = this;
                var trs = this.datagrid.find("tbody tr:has(." + Ladder.form.Components.fetchMark + "[data-rw=1])");
                for (var m = 0; m < trs.length; m++) {
                    var $this = $(trs[m]);
                    if (!Ladder.form.vaildForm($this)) continue;
                    var fv = Ladder.form.fetchFormValue($this, "data-fieldname", false);
                    for (var i = 0; i < me.columnModel.length; i++) {
                        var cm = me.getColumnModel(i);
                        if (cm["defaultValue"] != undefined && cm.fieldname != undefined) {
                            var p = cm.fieldname;
                            if (!fv.hasOwnProperty(p) || (!fv[p])) {
                                fv[p] = cm["defaultValue"];
                            }
                        }
                    }
                    if (fv) {
                        var so = { bean: fv, formers: me.getRowFormers($this), editModel: $this.attr("data-editmodel"), $tr: $this };
                        if(so.editModel=="edit" && !so.formers){
                            layer.msg('请检查待保存的数据!!', { icon: 2 });
                        }
                        nsave.push(so);
                    }
                }
                if (nsave.length < 1) return false;
                return nsave;
            },
            /**
             * 重新加载数据
             * @returns {}
             */
            reloadData: function () {
                var me = this;
                //如果是非连续选择，则清空checkbox的选择数据
                if(!me.settings.multiSelect||(!/keep/.test(me.settings.multiSelect.toString()))){
                    me.multiSelectData={};
                }
                for (var x = 0; x < me.griddata.length; x++) me.addRow(me.griddata[x], false, -1);
            },
            /**
             * 删除一行
             * @param $tr 默认当前行
             */
            removeRow: function ($tr) {
                if($tr==undefined)$tr = this.selectRow;
                var index=$tr.index();
                $tr.remove();
                this.datagrid.find("tbody tr:eq("+index+")").trigger("click");
            },
            /**
             * 删除一行
             * @param $tr 默认当前行
             */
            removeSelectRow: function () {
                var me=this;
                var $tbody=null;
                if(me.settings.freeze>0){
                    $tbody=me.settings.parentEL.find(".yui-datagrid-body .yui-datagrid-body-columns>.yui-datagrid-table tbody");
                }else{
                    $tbody = me.datagrid.find("tbody");
                }
                var ret=[];
                $tbody.find("tr>td:nth-child(1)>input.js-select:checked").each(function(){
                    $(this).parents("tr").remove();
                });
            },
            /**
             * 清空表格体的所有数据(不包含表头)
             */
            clear:function(){
                var content=this.datagrid.find("tbody");
                if(content.length<1)return;
                content.empty();
            },
            /**
             * 添加顶部自定义按钮
             *
             * 当表格为可编辑模式下有如下表格
             *
             * 新增一条 : js-addbtn
             * 修改数据: js-updatebtn
             * 提交保存: js-savebtn
             * 删除数据: js-delete
             * 当mask重复时，进行按钮功能替换
             * @param title
             * @param mask
             * @param fun
             * @returns {*}
             */
            addHeadButton: function (title, mask, fun) {
                var me = this;
                var saveExt=me.settings.saveExter;
                var btnview = $(me.settings.parentEL).find(".yui-datagrid-hbtns");
                if (!btnview || btnview.length < 1) return;
                var tempBtn=$("<button>"+title+"</button>");

                if (mask) {
                    var _type=Ladder.getType(mask);
                    if(_type=="String")tempBtn.addClass(mask);
                    if(_type=="Object"){
                        if(mask.hasOwnProperty("className")){
                            tempBtn.addClass(mask["className"]);
                            delete  mask.className;
                        }
                        for(var propname in mask){
                            tempBtn.attr(propname,mask[propname])
                        }
                    }
                }
                var btn = btnview.find("."+tempBtn.attr("class"));
                if (btn.length < 1) {
                    //var btn = $('<button class="' + mask + '">' + title + '</button>');
                    btnview.append(tempBtn);
                }else{
                    btn.replaceWith(tempBtn);
                }
                tempBtn.off();
                if (fun) {
                    tempBtn.click(function () {
                        fun(me)
                    });
                }
                return tempBtn;
            },
            /**
             *
             * 保存操作同步更新的远端，
             * @private
             * @param {json} 如果是按钮处理函数，必须传表格当前对象，在外部调用可用是空或者回调函数
             * @returns {}
             */
            saveDataToRemote: function (funobj) {
                var me;
                var fun;
                //为什么要这样做呢，因为如果是按钮点击事件中，this是按钮对象,所以必须回传
                if(!funobj)me = this;
                else{
                    if(Ladder.getType(funobj)=="Function"){//使用于外部调用
                        me=this;
                        fun=funobj;
                    }
                    else  me=funobj;
                }
                if (!me.settings.saveUrl) {
                    me.showMessage("您没有配置服务器请求路径", 2);
                    if (fun) fun({ statusCode: 500, message: "您没有配置服务器请求路径" });
                    return;
                }
                var tempsave = me.getNosavadata();
                if (!tempsave) {
                    if(fun)fun({statusCode:200,message:"没有任何行列数据需要保存"});
                    return;
                }
                for (var i = 0; i < tempsave.length; i++) {
                    var _onesave = tempsave[i];
                    var $tr = _onesave.$tr;
                    var id = Ladder.random(10);
                    $tr.attr("id", id);
                    var ddd = {
                        bean: JSON.stringify(_onesave.bean),
                        condition: JSON.stringify(_onesave.formers),
                        option: _onesave.editModel == "insert" ? 1 : 2,
                        rel: id
                    };
                    $.extend(ddd, me.settings.saveExter);
                    webajax(me.settings.saveUrl, ddd, function (json) {
                        if(fun)fun(json);
                        if (json.statusCode == 200) {
                            if (json.rel) {
                                var $re_tr = $("#" + json.rel);
                                if ($re_tr && $re_tr.length > 0) {
                                    me.setDisplay($re_tr);
                                    if ($re_tr.data("editmodel") == "insert") {
                                        me.replaceRow($("#" + json.rel), json.data);
                                        layer.msg('新增保存成功', { icon: 1 });
                                    } else {
                                        layer.msg('修改保存成功', { icon: 1 });
                                    }
                                }
                            } else {
                                layer.msg('请检查待保存的数据!!', { icon: 2 });
                            }
                        }else{
                            layer.msg(json.message, { icon: 2 });
                        }
                    });
                }
            },
            /**
             *
             * 保存操作同步更新的远端
             * @param {} me
             * @returns {}
             */
            deleteDataToRemote: function (me) {
                if (!me) me = this;
                var $tr = me.selectRow;
                if (!$tr) {
                    me.showMessage("请选择您要删除的行列", 2);
                    return;
                }
                if (!me.settings.saveUrl) {
                    me.showMessage("您没有配置远端请求路径", 2);
                    return;
                }
                if ($tr.data("editmodel") == "insert"){
                    me.removeRow($tr);
                    return;
                }
                var condition = me.getRowFormers($tr);
                if(!condition)return;
                var ddd = {
                    condition: JSON.stringify(condition),
                    option: -1
                };
                ddd = $.extend(ddd, me.settings.saveExter);
                layer.confirm('请您确认是否删除', {
                    btn: ['确认删除', '取消返回'], //按钮
                    shade: false //不显示遮罩
                }, function () {
                    webajax(me.settings.saveUrl, ddd, function (json) {
                        if (json.statusCode == 200) {
                            me.removeRow($tr);
                            layer.msg('数据已经删除啦！', { icon: 1 });
                        }
                    });
                });
            },
            /**
             * 显示提示信息，属于内部方法
             * @private
             * @param text
             * @param iconindex
             */
            showMessage: function (text, iconindex) {
                if (!text) return;
                if (iconindex == undefined) iconindex = 1;
                layer.msg(text, { icon: iconindex });
            },
            /**
             * 选择框检查器
             * @private
             * @param event
             */
            multiCheck: function (event) {
                var $this = $(this);
                var me = event.data["me"];
                var $tr=$this.parents("tr");
                var gendata = me.fetchgendata($tr);
                //如果有选择事件
                if(me.settings.onCheck){
                    me.settings.onCheck("one",$this,$this.prop("checked"),$tr.data("rowData"),$tr);
                }
                if ($this.prop("checked")) {
                    if (me.settings.multiSelect == "only") me.multiSelectData = new Object();
                    me.multiSelectData[gendata] = $tr.data("rowData");
                } else {
                    delete me.multiSelectData[gendata];
                }
                if (me.settings.multiSelect == "only") {
                    var $other = me.datagrid.find("tbody tr td:nth-child(1) input.js-select:checked").not($this);
                    if ($other.length < 1) return;
                    var othergendata = me.fetchgendata($other.parents("tr"));
                    delete me.multiSelectData[othergendata];
                    $other.prop("checked", false);
                    return;
                }
                var total = me.datagrid.find("tbody tr td:nth-child(1) input.js-select").length;
                var checknum = me.datagrid.find("tbody tr td:nth-child(1) input.js-select:checked").length;
                var $td = me.datagrid.find("thead td:eq(0)");
                switch (checknum) {
                    case 0:
                        $td.html("全选");
                        break;
                    case total:
                        $td.html("不选");
                        break;
                    default:
                        $td.html("反选");
                }
            },
            /**
             * 获取表格上选择器勾选的数据，—>把对象数据转换成数据
             * 如果multiSelect为keep进行多页勾选数据的检出
             * @param isfullData  是否选择的全部数据,默认只选择索引值
             */
            fetchSelectData:function(isfullData){
                var me=this;
                if(this.settings.multiSelect==="keep"){
                    var re_t=[];
                    if(!this.multiSelectData)return re_t;
                    for(var keyName in this.multiSelectData){
                        if(isfullData)re_t.push(this.multiSelectData[keyName])
                        else re_t.push(keyName);
                    }
                    return re_t;
                }
                var $tbody=null;
                if(me.settings.freeze>0){
                    $tbody=me.settings.parentEL.find(".yui-datagrid-body .yui-datagrid-body-columns>.yui-datagrid-table tbody");
                }else{
                    $tbody = me.datagrid.find("tbody");
                }
                var ret=[];
                $tbody.find("tr>td:nth-child(1)>input.js-select:checked").each(function(){
                    var $tr=$(this).parents("tr");
                    if(isfullData){
                        ret.push($tr.data("rowData"));
                    }else{
                        var gendata = me.fetchgendata($tr);
                        if(gendata)ret.push(gendata);
                    }
                });
                return ret;
            },
            /**
             * 获取唯一ID值,默认返回一个值，这个方法和getRowFormers()有部分重叠，后者组装成数组对象，前者组数据
             * @param _tr
             * @param one
             * @returns {*}
             */
            fetchgendata: function (_tr, one) {
                if (_tr == undefined || (!_tr)) _tr = this.selectRow;
                var $tr = $(_tr);
                if ($tr.length < 1) return false;
                var gens = $tr.attr("data-gens");
                if (!gens) return false;
                var genarray = gens.split("|");
                if (one == undefined || one) {
                    return $tr.attr("data-" + genarray[0] + "-value");
                }
                else {
                    var re_t = new Array();
                    for (var dat in genarray) { re_t.push(dat); }
                    return re_t;
                }
            },
            /**
             * 创建尾部视图
             * @private
             * @param pel
             * @param option
             */
            createFootView: function (pel, option) {
                var me = this;
                if (!pel) pel = me.settings.parentEL;
                var $pel = $(pel);
                if ($pel.length < 1) return;//如果没有父级元素
                var $divDefault = $("<div class='yui-datagrid-foot'></div>");//创建底部容器
                $pel.append($divDefault);//追加在尾部
                if (/(default)|(pager)/i.test(option.fitView) && !option.pageEL){
                    var sd = $("<div class='yui-datagrid-pager'></div>");//分页组件
                    //me.settings.parentEL = sd;
                    me.settings.pageEL = sd;
                    var select = $("<select class='pagesize'></select>");
                    var pageconfig=new Array();
                    if(option.pageShowNum)me.settings.pageShowNum=option.pageShowNum;
                    if(me.settings.pageShowNum){
                        var pages=me.settings.pageShowNum.split("|");
                        for(var i=0;i<pages.length;i++) {
                            var pageinfo = pages[i].split(":");
                            pageconfig.push({value:pageinfo[0],selected:pageinfo[pageinfo.length-1]=="selected"?true:false});
                        }
                    }else{
                        pageconfig.push({value:"20",selected:true});
                    }
                    for (var i = 0; i < pageconfig.length; i++) {
                        select.append("<option value='" + pageconfig[i].value + "' " + (pageconfig[i].selected?"selected":"") + ">" + pageconfig[i].value + "</option>");
                    }
                    select.change(function() {
                        me.gopage($(me.settings.pageEL).find(".js-gopage").val(),$(this).val())
                    });
                    var total = $("<span class='total'></span>");
                    var displaytext = $("<span class='display'></span>").append("每页显示").append(select).append(" 共 ").append(total).append(" 条");
                    var btns = $("<div class='pagebtnAara'></div>");
                    var first = $("<a class='actionbtn js-first'>首页</a>").click(function() {me.gopage(1)});
                    var per = $("<a class='actionbtn js-previous'>上一页</a>").click(function () { me.gopage($(this).attr("data-page")) });
                    var next = $("<a class='actionbtn js-next'>下一页</a>").click(function () { me.gopage($(this).attr("data-page")) });
                    var end = $("<a class='actionbtn js-end'>尾页</a>").click(function () { me.gopage($(this).attr("data-page")) });
                    var input = $("<input class='js-gopage'>").css({ width: "23px", height: '18px',"text-align":"center","line-height":"18px" }).change(function () { me.gopage($(this).val()) });
                    btns.append(first).append(per).append(" 第 ").append(input).append(" <span class='pagecount'>1</span>").append(next).append(end);
                    sd.append(displaytext);
                    sd.append(btns);
                    $divDefault.append(sd);
                    //增加统计
                    if(/count/i.test(option.fitView)){
                        var $countbtn=$("<button class='counterbtn'>统计</button>").prependTo(sd);//统计按钮
                        var $countView =$("<div class='counterView' style='display: none'></div>").appendTo($divDefault);//统计视图
                        //右侧的关闭按钮
                        var $close=$("<span class='closeicon'></span>");
                        $close.appendTo($countView).click(function(){
                            $countbtn.prependTo(sd);
                            $countView.hide();
                        });
                        $countbtn.click(function(){
                            if($countView.is(":hidden")){
                                $countbtn.data("step",0);
                                $countView.find(".counterItem").remove();
                                $countView.show(1000);
                                $countbtn.appendTo($countView);
                                //循环遍历列模型中是否含有统计选项,暂时未实现扩展列的统计，预留扩展！！！   ->2015-12-30
                                var counterColumns=[];
                                for(var i=0;i<me.columnModel.length;i++){
                                    if(me.columnModel[i].counter){
                                        counterColumns.push($.extend({"marker":i},me.columnModel[i]))
                                    }
                                }
                                if(me.extColumnModel&&me.extColumnModel.length>0){
                                    for(var i=0;i<me.extColumnModel.length;i++){
                                        if(me.extColumnModel[i].counter){
                                            counterColumns.push($.extend({"marker":"ext_"+i},me.extColumnModel[i]))
                                        }
                                    }
                                }

                                if(counterColumns.length<1)return;
                                for(var i=0;i<counterColumns.length;i++){
                                    var cm=counterColumns[i];
                                    var handleObject=counterColumns[i].counter;
                                    if(handleObject){
                                        var _type =Ladder.getType(handleObject);
                                        var $countItem =$("<div class='counterItem'><span class='title'></span><span class='value'></span><span class='unit'></span></div>");
                                        $countView.append($countItem);
                                        switch (_type){
                                            case "Function":
                                                var vals=[];
                                                me.datagrid.find("tbody td[data-modelindex="+cm.marker+"]").each(function(){
                                                    vals.push($(this).html());
                                                });
                                                var re_t = handleObject(vals,$countItem);
                                                if(re_t){
                                                    if(Ladder.getType(re_t)==="Object"){
                                                        $countItem.find(".title").html((re_t.title?re_t.title:cm.title)+":");
                                                        $countItem.find(".value").html(re_t.value);
                                                        $countItem.find(".unit").html(re_t.unit);
                                                    }else{
                                                        $countItem.find(".title").html(cm.title+":");
                                                        $countItem.find(".value").html(re_t);
                                                    }
                                                }
                                                break;
                                            case "Object":
                                                $countItem.find(".title").html((handleObject.title?handleObject.title:cm.title)+":");
                                                $countItem.find(".value").html(handleObject.value);
                                                $countItem.find(".unit").html(handleObject.unit);
                                                break;
                                            case "String"://文本型
                                                $countItem.find(".title").html(cm.title+":");
                                                $countItem.find(".value").html(handleObject);
                                                break;
                                            case "Boolean":
                                                if(handleObject){//此处判断多余
                                                    var displayvalue=0;
                                                    me.datagrid.find("tbody td[data-modelindex="+cm.marker+"]").each(function(){
                                                        var v=$(this).html();
                                                        if(v.length>0){
                                                            var iv =parseFloat(v);
                                                            if(!isNaN(iv))displayvalue+=iv;
                                                        }
                                                    });
                                                    $countItem.find(".title").html(cm.title+":");
                                                    $countItem.find(".value").html(displayvalue);
                                                }else $countItem.remove();
                                                break;
                                            default:
                                                break;
                                        }
                                        $countItem.data("modelindex",cm.marker);
                                        //$countItem.css("position","absolute").animate({
                                        //    left:"+"+(me.datagrid.find("tbody tr:eq(1) td[data-modelindex="+i+"]").offset().left-$countItem.offset().left) +"px"
                                        //},1000);
                                    }
                                }
                            }else{
                                //移动统计项到表格列边缘
                                if($countbtn.data("step")==0){
                                    $countbtn.data("step",1);
                                    if(me.datagrid.find("tbody tr:eq(0)").length<1)return;
                                    $countView.find(".counterItem").each(function(){
                                        var $item=$(this);
                                        var $gtd=me.datagrid.find("tbody tr:eq(0) td[data-modelindex="+$item.data("modelindex")+"]");
                                        var gtdleft=$gtd.offset().left*2+$gtd.width();
                                        var ileft=$item.offset().left;//相对位置
                                        var dist=gtdleft/2 -ileft;
                                        $item.css("position","absolute").animate({
                                            left:"+"+dist +"px"
                                        },1000);
                                    });
                                    return;
                                }
                                //置回原貌显示
                                if($countbtn.data("step")==1){
                                    $close.trigger("click");
                                }
                            }

                            //$countView.toggle(1500,function(){
                            //    if(!$(this).is(":hidden")){
                            //
                            //    }
                            //});
                        });
                    }

                }
            },
            /**
             * 跳到指定页面
             * @param {} pageNo
             * @param {} pageData 默认为表格的分页数据
             * @returns {}
             */
            gopage:function(pageNo,pageSize) {
                var me = this;
                var pageData = me.condition.pager;
                if(me.settings.onPaging){
                    var re_t=me.settings.onPaging(pageNo,pageSize,pageData);
                    if(re_t===false){
                        return;
                    }
                }
                if(pageSize!=undefined&&pageSize!=pageData.pageSize){//重新分页
                    if(me.settings.queryUrl&&me.settings.queryData){
                        me.settings.queryData.psize = pageSize;
                        me.setCondition("pager");
                        me.requestData();
                        return;
                    }
                }
                pageNo = pageNo * 1;
                if (pageNo < 1)pageNo = 1;
                if (pageNo > pageData.pageCount)pageNo = pageData.pageCount;
                me.condition.pager.pageNumber = pageNo;
                if(me.settings.queryUrl) me.requestData();
            },
            /***
             * 重新分页
             * @param pageNo 页号
             * @param pageSize 页数
             * @param countoffset 记录数的偏移量
             */
            repage: function (pageNo, pageSize,countoffset) {
                var me = this;
                var pageData = me.condition.pager;
                if (me.settings.onPaging) {
                    var re_t = me.settings.onPaging(pageNo, pageSize, pageData);
                    if (re_t === false) {
                        return;
                    }
                }
                if (pageSize != undefined&&pageSize!=me.condition.pager.pageSize) {//重新分页
                    if (me.settings.queryUrl && me.settings.queryData) {
                        me.settings.queryData.psize = pageSize;
                        me.setCondition("pager",{pageNumber:pageNo});
                        me.requestData();
                        return;
                    }
                }
                if(pageData.recordCount&&countoffset){
                    pageData.recordCount+=countoffset;
                    pageData.pageCount=Math.ceil(pageData.recordCount*1.000/pageData.pageSize)
                }
                pageNo = pageNo * 1;
                if (pageNo < 1) pageNo = 1;
                if (pageNo > pageData.pageCount) pageNo = pageData.pageCount;
                pageData.pageNumber = pageNo;
                if (me.settings.queryUrl) me.requestData();
            },

            /**
             * 创建头部视图->
             * 在方法内，this.settings的默认值还没有组装，option里的值全部是实例化时提供的
             * @private
             * @param pel
             * @param option
             * @param genid
             */
            createHeadView: function (pel,option,genid) {
                var me = this;
                if (!pel) pel = me.settings.parentEL;
                if (!pel) return;
                var $pel = $(pel);
                if ($pel.length < 1) return;
                var $divDefault = $("<div class='yui-datagrid-head yui-datagrid-borderline'>");//第一行表上部
                var $gridhead = $('<div class="yui-datagrid-head js-formbtns hide"></div>');//第二行表上部
                //建立标题和设置view
                if (/(default)|(setting)|(caption)|(export)/i.test(option.fitView)) {
                    $pel.prepend($divDefault);
                    $divDefault.prepend($('<h4 class="caption">' + (option.hasOwnProperty("title")?option.title:"") + '</h4>'));
                    var setbtn = $("<button title='设置' class='setting iconsetting'>").hide();
                    if(/(default)|(setting)/i.test(option.fitView)){
                        setbtn.show();
                    }
                    //导出电子表格
                    var exportbtn = $("<a title='导出Execl' class='setting exportbtn'>导出Execl</a>").hide();
                    if (/(export)/i.test(option.fitView)) {
                        exportbtn.show();
                    }
                    exportbtn.click(function() {
                        me.createExportView();
                        //var $this = $(this);
                        //var param = me.settings.queryData;
                        //param.condition = me.condition.forms;
                        //param.columns = me.condition.columnString;
                        //param = $.param(param);
                        //var url = Ladder.Service.parseUrl(URLS.URL_FileDownLoad);
                        //if (param) url += "?" + param;
                        //if (url) {
                        //    $this.attr("href", url);
                        //} else {
                        //    layer.msg("当前条件下不容许导出");
                        //}
                    });
                    $divDefault.append(setbtn);
                    $divDefault.append(exportbtn);
                    var settingbtns = $("<ul class='setting'></ul>");
                    $divDefault.append(settingbtns);
                    settingbtns.hide();
                    setbtn.on("click", function () {
                        settingbtns.toggle("slow");
                    });
                    //基本设置
                    settingbtns.append($("<li><button class='settingbtn btn-default'>基本设置</button></li>").on("click", function () {
                        me.showSettingView('basic', me.basicHtml(), false, false, "数据表格基本设置 (部分属性受限于CSS样式)");
                    }));
                    //参数设置
                    settingbtns.append($("<li><button class='settingbtn btn-default'>运行参数</button></li>").on("click", function () {
                        me.showSettingView('args', me.argsHtml(), '420px', '340px',"运行期参数");
                    }));
                    //字段设置
                    settingbtns.append($("<li><button class='settingbtn btn-default'>字段设置</button></li>").on('click', function () {
                        me.showSettingView("columns", me.columnsHtml(), '504px', '340px', "字段管理与设置");
                    }));
                    //过滤查询
                    settingbtns.append($("<li><button class='settingbtn btn-default'>高级过滤</button></li>").on('click', function () {
                        me.showSettingView("query", me.queryHtml(), '720px', '450px', "高级过滤查询");
                    }));
                }
                //if (/default.*(queryform)|(button)/i.test(option.fitView)) {
                if (/(default)|(queryform)|(button)/i.test(option.fitView)) {
                    $pel.append($gridhead);
                    //queryform部分
                    if (option.queryFormAction&&/(default)|(queryform)/i.test(option.fitView)) { //表单的动作行为,如果不空建立查询表单
                        if (!option.queryFormEL || $(option.queryFormEL).length < 1) {
                            var queryformel = $('<div class="yui-dgqf"><ul></ul></div>');
                            if (!option.queryFormEL) {
                                option.queryFormEL = queryformel;
                                $gridhead.append(queryformel);
                                $gridhead.show();
                            }
                        }
                        me.runstatus.B_queryFrom = false;//queryform 建立状态位，现表单查询条件还没有组装
                    }
                    //按钮部分
                    var buttons = $('<div class="yui-datagrid-hbtns"></div>');
                    if(/button[s]?:first/.test(option.fitView)){
                        $divDefault.append(buttons);
                    }else{
                        $gridhead.show().append(buttons);
                    }
                    //默认表格的CURD按钮
                    if (option.saveUrl&&/(default)|(button)/i.test(option.fitView)) {
                        me.addHeadButton("新增一条", "js-addbtn", function () {
                            me.addRow(null, true);
                        });
                        me.addHeadButton("修改数据", "js-updatebtn", function () {
                            me.setRowEdit(me.selectRow);
                        });
                        me.addHeadButton("提交保存", "js-savebtn", me.saveDataToRemote);
                        me.addHeadButton("删除数据", "js-delete", me.deleteDataToRemote);
                    }
                }
                //必填字段->用于自定义表宽功能
                var $rel=$("<div style='position:relative;width: 100%' class='columnresize'></div>");
                $pel.append($rel);
            },
            /**
             * 创建导出表格的选项视图
             * @param me
             */
            createExportView:function(me){
                if(!me)me=this;
                var viewid=Ladder.uuid();
                var layerid=layer.open({
                    title:"导出Excel选项",
                    type:1,
                    content:"<div class='export-view' id='"+viewid+"'>" +
                    "<button class='btn-default pagedata'>导出本页数据</button>"+
                    "<button class='btn-default alldata' style='display: none'>导出全部数据</button>"+
                    "</div>",
                    area:['250px', '180px']
                });
                //如果是自动或者全部数据选项，显示操作按钮
                if(/(auto)|(all)/.test(me.settings.exportType)){
                    $("#"+viewid+" .alldata").show().click(function(){
                        me.exportDate.call(me,1);
                        layer.close(layerid);
                    });
                }
                //导出本页的监听
                $("#"+viewid+" .pagedata").click(function(){
                    me.exportDate.call(me,0);
                    layer.close(layerid);

                });
            },

            /**
             * 获取当前请求的查询方法
             * @returns {Object/String}
             */
            fetchQueryCondition:function(stringfy) {
                var me = this;
                data = me.settings.queryData;//置默认
                if (me.condition && Ladder.getType(me.condition) == "Object") {//自身的condition
                    //如果初始化参数中含有condition，进行继承
                    if(data.hasOwnProperty("condition")) {
                        data.condition= $.extend(Ladder.toJSON(data.condition),me.condition);
                    }else {data.condition=me.condition;}
                }
                if (stringfy) {
                    return data;

                } else {
                    if (data.condition && Ladder.getType(data.condition) == "Object") {
                        data.condition = JSON.stringify(data.condition);
                    }
                    return $.param(data);
                }
            },
            /**
             * 显示系统设置,以及监听元素事件-->代码书写的比较累赘，有待改进
             * @private
             * @param type
             * @param html
             * @param k
             * @param h
             * @param title
             */
            showSettingView: function (type, html, k, h, title) {
                if (!type) return;
                var me = this;
                layer.open({
                    title: title ? title : "基本设置",
                    type: 1,
                    area: [(k ? k : '420px'), (h ? h : '300px')], //宽高
                    content: html
                });
                //字段设置
                if (type == "columns") {
                    //字段向上 监听
                    $(".yui-datagrid-settingpage button.js-up").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        var $per = $selected.prev().first();
                        $per.before($selected);
                    });
                    //字段向下 监听
                    $(".yui-datagrid-settingpage button.js-down").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        var $next = $selected.next().first();
                        $next.after($selected);
                    });
                    //字段合并 监听
                    $(".yui-datagrid-settingpage button.js-join").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        if ($selected.length < 2) {
                            layer.msg("合并字段必须大于两个字段选项", { icon: 2 });
                            return;
                        }
                        var $first = $($selected[0]);
                        for (var i = 1; i < $selected.length; i++) {
                            var $this = $($selected[i]);
                            $this.attr("data-join", $first.val());
                            var text = $this.text();
                            if (/\[合并:.*\]/.test(html)) {
                                text.replace(/\[合并:.*\]/, "[合并:" + $first.attr("data-title") + "]");
                            } else {
                                text += "[合并:" + $first.attr("data-title") + "]";
                            }
                            $this.html(text);
                        }
                    });
                    //字段分解 监听
                    $(".yui-datagrid-settingpage button.js-split").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected[data-join]");
                        if ($selected.length < 1) {
                            layer.msg("您选择的字段不存在合并字段", { icon: 3 });
                            return;
                        }
                        $selected.each(function () {
                            var $this = $(this);
                            $this.removeAttr("data-join");
                            $this.html($this.html().replace(/\[合并:.*\]/,""));
                        });
                    });
                    //字段变名 监听
                    $(".yui-datagrid-settingpage button.js-change").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        if ($selected.length != 1) {
                            layer.msg("请选择一个字段选项", { icon: 2, time: 2000 });
                            return;
                        }
                        var layerno = layer.confirm("<input class='js-rename' value='" + $selected.attr("data-title") + "' style='width:200px;'>",
                            { title: '请输入字段的新命名' }, function () {
                                var newname = $(".js-rename").val();
                                var oldname = $selected.attr("data-title");
                                if (newname.length > 1 && newname != oldname) {
                                    $selected.html($selected.html().replace(oldname, newname));
                                    $selected.attr("data-title", newname);
                                    //合并到此字段的列s
                                    $(".yui-datagrid-settingpage .selectedcolumns option[data-join='" + $selected.val() + "']").each(function () {
                                        $(this).html($(this).html().replace(/\[合并:.*\]/, "[合并:" + newname + "]"));
                                    });
                                }
                                layer.close(layerno);
                            });
                    });
                    //字段变宽 监听
                    $(".yui-datagrid-settingpage button.js-width").on("click", function () {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        if ($selected.length < 1) {
                            layer.msg("请选择一个字段选项", { icon: 2, time: 2000 });
                            return;
                        }
                        var defvalue = $selected.attr("data-width") == "false"?"默认" : $selected.attr("data-width");
                        var layerno = layer.confirm(
                            "<input class='js-rename' value='" + defvalue + "' style='width:200px;'>",
                            { title: '请输入字段的新显示宽度' },
                            function () {
                                var newname = $(".js-rename").val();
                                //if 输入的 不等于旧值 长度大于1 是 52px 或者 50% 等
                                if (newname.length > 1 && (newname.replace(/px/i, '') * 1 > 0 || newname.indexOf('%') > 0)) {
                                    $selected.each(function() {
                                        var $this = $(this);
                                        $this.attr("data-width", newname);
                                        var html = $this.text();
                                        if (/\[宽度:.*\]/.test(html)) {
                                            if (/%$/.test(newname)) {
                                                $this.html(html.replace(/\[宽度:.*\]/, "[宽度:" + newname + "]"));
                                            } else {
                                                newname = newname.replace(/px/i, '') + "px";
                                                $this.html(html.replace(/\[宽度:.*\]/, "[宽度:" + newname + "]"));
                                            }
                                        } else {
                                            $this.html(html + "[宽度:" + newname + "]");
                                        }
                                    });
                                } else {
                                    layer.msg("已经修改成默认宽度");
                                    $selected.each(function() {
                                        var $this = $(this);
                                        $this.attr("data-width", false);
                                        $this.html($this.html().replace(/\[宽度:.*\]/, ''));
                                    });
                                }
                                layer.close(layerno);
                            }
                        );
                    });
                    //字段隐藏 监听
                    $(".yui-datagrid-settingpage button.js-hidden").on("click", function() {
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if ($selects.length < 1) return;
                        var $selected = $selects.find("option:selected");
                        if ($selected.length < 1) {
                            layer.msg("请选择一个字段选项", { icon: 2, time: 2000 });
                            return;
                        }
                        $selected.each(function() {
                            var $this = $(this);
                            var text = $this.text().replace(/\[隐\]/, '');
                            var oldvalue = $selected.attr("data-isshow");
                            if (oldvalue == "false") {
                                $this.attr("data-isshow", true);
                            } else {
                                $this.attr("data-isshow", false);
                                text += "[隐]";
                            }
                            $this.html(text);
                        });
                    });
                    //增加字段 监听
                    $(".yui-datagrid-settingpage button.js-addselected").on("click", function () {
                        var fields = $(".yui-datagrid-settingpage .fullcolumns option:selected");
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns");
                        if (fields.length < 1 || $selects.length < 1) {
                            layer.msg("您没有选择字段", { icon: 2 });
                            return;
                        }
                        fields.each(function () {
                            var $this = $(this);
                            $selects.append($this);
                        });
                        $(".yui-datagrid-settingpage .fullcolumns option:first").prop("selected", true);
                    });
                    //删除字段 监听
                    $(".yui-datagrid-settingpage button.js-delselected").on("click", function () {
                        var fields = $(".yui-datagrid-settingpage .fullcolumns");
                        var $selects = $(".yui-datagrid-settingpage .selectedcolumns option:selected");
                        if (fields.length < 1 || $selects.length < 1) {
                            layer.msg("您没有选择字段", { icon: 2 });
                            return;
                        }
                        $selects.each(function () {
                            var $this = $(this);
                            //非gen字段都可以移动
                            if (!$this.attr("data-gen")) fields.append($this);
                        });
                        $(".yui-datagrid-settingpage .selectedcolumns option:first").prop("selected", true);
                    });

                }
                if (type == "query") {

                }
                $(".yui-datagrid-settingpage .savebtn").click(function () {
                    if (type == "columns") {
                        var columnString = "";
                        //分析各个字段属性设置
                        $(".yui-datagrid-settingpage .selectedcolumns option").each(function () {
                            var $this = $(this);
                            columnString += $this.val() + ",";
                            var config = {
                                isshow: $this.attr("data-isshow")=="false"?false:true,
                                title: $this.attr("data-title"),
                                join: $this.attr("data-join") ? $this.attr("data-join") : false,
                                width: $this.attr("data-width") == "false" ? false : $this.attr("data-width")
                            };
                            me.setColumnConfig($this.val(), config);
                        });
                        me.setCondition("columnString",columnString ? columnString.substr(0, columnString.length - 1) : me.condition.columnString);
                        //if(!me.settings.queryData.hasOwnProperty("condition"))me.settings.queryData.condition=new Object();
                        me.requestData();
                    }
                    if (type == "basic") {
                        var config = Ladder.form.fetchFormValue(".yui-datagrid-settingpage", "id", false);
                        config.gridClass = config.gridClass == "默认" ? 'yui-datagrid' : config.gridClass;
                        config.selectClass = config.selectClass == "默认" ? 'currentSelect' : config.selectClass;
                        config.sorter = config.sorter == "true" ? true : false;
                        config.resizable = config.resizable == "true" ? true : false;
                        config.rowHeight = config.rowHeight * 1 ;
                        config.titleRowHeight = config.titleRowHeight * 1;
                        $.extend(me.settings, config);
                        var $title = $(me.settings.parentEL).find(".yui-datagrid-head .caption");
                        if ($title.length > 0) {
                            $title.html(config.title);
                        }
                        me.requestData();
                    }
                    if (type == "query") {
                        var querycondtion = new Array();
                        var $diyform = $(".yui-datagrid-settingpage .diyquery");
                        $diyform.each(function () {
                            var querydata = Ladder.form.fetchFormValue($(this), "data-bind", false);
                            if (querydata.op == "like") {//在like条件上增加%
                                if (!/^%/.test(querydata.value)) querydata.value = "%" + querydata.value;
                                if (!/%$/.test(querydata.value)) querydata.value = querydata.value + "%";
                            }
                            querycondtion.push(querydata);
                        });
                        var param = {
                            condition: JSON.stringify({ forms: JSON.stringify(querycondtion) }),
                        };
                        me.multiSelectData = new Object();
                        me.condition.forms = JSON.stringify(querycondtion);
                        me.condition.pager = null;
                        me.loadRemote();
                    }
                });
            },
            /**
             * 创建基本设置的html代码段
             * @private
             * @returns {*|string}
             */
            basicHtml: function () {
                var me = this;
                var $page = $("<div class='yui-datagrid-settingpage'></div>");
                var html = '<div class="row">' +
                    '<span>组件标题</span> ' +
                    '<input type="text" id="title" class="js-yui longinput" data-rw="1" value="' + me.settings.title + '">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>标题行高</span> ' +
                    '<input type="text" id="titleRowHeight" class="js-yui shortinput" data-rw="1" value="' + me.settings.titleRowHeight.toString().replace("px","") + '">' +
                    '<b class="bigword">px</b>' +
                    '<span style="margin-left:30px;">表格高度</span> ' +
                    '<input type="text" id="rowHeight" class="js-yui shortinput" data-rw="1" value="' + me.settings.rowHeight.toString().replace("px", "") + '">' +
                    '<b class="bigword">px</b>' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>表格样式</span> ' +
                    '<input type="text" id="gridClass" class="js-yui shortinput" data-rw="1" value="默认" data-value="yui-datagrid">' +
                    '<span style="margin-left:47px;">选区样式</span> ' +
                    '<input type="text" id="selectClass" class="js-yui shortinput" data-rw="1" value="默认" data-value="currentSelect">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>是否排序</span> ' +
                    '<select type="text" id="sorter" class="js-yui" data-rw="1" style="width:90px;">' +
                    '<option value="false" '+(me.settings.sorter?"":"selected")+'>不排序</option>' +
                    '<option value="true" ' + (me.settings.sorter ? "selected" : "") + '>排序</option>' +
                    '</select>' +

                    '<span style="margin-left:42px;">手动调宽</span> ' +
                    '<select type="text" id="resizable" class="js-yui" data-rw="1" style="width:90px;">' +
                    '<option value="false" selected>禁用</option>' +
                    // '<option value="true">启用</option>' +
                    '</select>' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>水平对齐</span> ' +
                    '<select type="text" id="columnAlign" class="js-yui" data-rw="1" style="width:90px;">' +
                    '<option value="center" ' + (me.settings.columnAlign == 'center'?"selected":"") + '>居中</option>' +
                    '<option value="left" ' + (me.settings.columnAlign == 'left' ? "selected" : "") + '>居左</option>' +
                    '<option value="right" ' + (me.settings.columnAlign == 'right' ? "selected" : "") + '>居右</option>' +
                    '</select>' +

                    '<span style="margin-left:42px;">垂直对齐</span> ' +
                    '<select type="text" id="columnVAlign" class="js-yui" data-rw="1" style="width:90px;">' +
                    '<option value="middle" ' + (me.settings.columnVAlign == 'middle' ? "selected" : "") + '>居中</option>' +
                    '<option value="top" ' + (me.settings.columnVAlign == 'top' ? "selected" : "") + '>居上</option>' +
                    '<option value="bottom" ' + (me.settings.columnVAlign == 'bottom' ? "selected" : "") + '>居下</option>' +
                    '</select>' +
                    '</div>'
                ;
                $page.append(html);
                $page.append("<button class='savebtn'>保存</button>");
                return $page.get(0).outerHTML;

            },
            /**
             * 创建运行期参数的html代码段
             * @private
             * @returns {*|string}
             */
            argsHtml: function () {
                var me = this;
                var $page = $("<div class='yui-datagrid-settingpage'></div>");
                var html = '<div class="row">' +
                    '<span>请求路径</span> ' +
                    '<input type="text" id="queryUrl" class="js-yui longinput" data-rw="1" value="' + me.settings.queryUrl+ '">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>请求参数</span> ' +
                    '<textarea id="queryData" class="js-yui longinput" data-rw="1" style="height:100px;">' + JSON.stringify(me.settings.queryData) + '</textarea>' +
                    '</div>' +

                    '<div class="row">' +
                    '<span>列模数据</span> ' +
                    '<textarea id="queryData" class="js-yui longinput" data-rw="1" style="height:100px;">' + JSON.stringify(me.columnModel) + '</textarea>' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>滤列数据</span> ' +
                    '<textarea id="queryData" class="js-yui longinput" data-rw="1" style="height:100px;">' + JSON.stringify(me.columnFilter) + '</textarea>' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>主体数据</span> ' +
                    '<textarea id="queryData" class="js-yui longinput" data-rw="1" style="height:100px;">' + JSON.stringify(me.griddata) + '</textarea>' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>查询动作</span> ' +
                    '<input type="text" id="queryFormAction" class="js-yui longinput" data-rw="1" value="' + me.settings.queryFormAction + '">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>修改路径</span> ' +
                    '<input type="text" id="saveUrl" class="js-yui longinput" data-rw="1" value="' + me.settings.saveUrl + '">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>修改参数</span> ' +
                    '<input type="text" id="saveExter" class="js-yui longinput" data-rw="1" value="' + JSON.stringify(me.settings.saveExter) + '">' +
                    '</div>' +
                    '<div class="row">' +
                    '<span>视图组件</span> ' +
                    '<input type="text" id="fitView" class="js-yui longinput" data-rw="1" value="' + me.settings.fitView + '">' +
                    '</div>';
                $page.append(html);
//            $page.append("<button class='savebtn'>保存</button>");
                return $page.get(0).outerHTML;
            },
            /**
             * 创建字段管理的html代码段
             * @private
             * @returns {*}
             */
            columnsHtml: function () {
                var me = this;
                if (!me.fullColumns || me.fullColumns.length < 1) return '<h1 style="margin:100px auto;">列字段未获得，请检查接口</h1>';
                var $page = $("<div style='width: 500px;height: auto;margin: 2px auto'></div>");
                var $leftdiv = $('<select class="columns fullcolumns" style="float:left;width:180px;height:240px" multiple="multiple"></select>');
                var $rightdiv = $('<select class="columns selectedcolumns" style="float:left;width:200px;height:240px" multiple="multiple"></select>');
                var $leftbtn = $("<button class='js-addselected btn-default'>→</button>");
                var $rightbtn = $("<button class='js-delselected btn-default'>←</button>");
                var $upbtn = $("<button class='js-up btn-default'>向上↑</button>");
                var $downbtn = $("<button class='js-down btn-default'>向下↓</button>");
                var $joinbtn = $("<button class='js-join btn-default'>合并<></button>");
                var $splitbtn = $("<button class='js-split btn-default'>分解><</button>");
                var $changebtn = $("<button class='js-change btn-default'>变名卍</button>");
                var $widthbtn = $("<button class='js-width btn-default'>调宽↔</button>");
                var $hideenbtn = $("<button class='js-hidden btn-default'>隐藏✄</button>");
                $page.append($leftdiv);
                $page.append($("<div class='controlbtn' style='margin-top:70px;'></div>").append($leftbtn).append($rightbtn));
                $page.append($rightdiv);
                $page.append($("<div class='controlbtn'></div>").append($upbtn).append($downbtn).append($joinbtn).append($splitbtn).append($changebtn).append($widthbtn).append($hideenbtn));
                for (var i = 0; i < me.fullColumns.length; i++) {
                    var data = me.fullColumns[i];
                    var $option = $("<option></option>");
                    $option.html(data.title);
                    $option.attr('data-title', data.title);
                    $option.attr("value", data.as ? data.as : data.fieldname);
                    $option.attr("data-width", false);
                    $option.attr("data-isshow", true);
                    var index = me.findModelIndex(data.as ? data.as : data.fieldname);//查找表格字段的定位
                    if (index > -1) {
                        var col = me.getColumnModel(index); //获取配置项对象
                        $option.html(col.title); //更换标题
                        $option.attr('data-title', col.title);
                        if (col.width) {//替代默认宽度
                            $option.attr("data-width", col.width);
                            $option.html($option.html() + "[宽度:" + col.width + "]");
                        }
                        if (col.isshow==undefined||col.isshow) $rightdiv.append($option);
                        else {
                            //如果是gen字段中uuid和id必须选择
                            if (col.gen && (col.gen.toLowerCase() == "uuid" || col.gen.toLowerCase() == "id")) $rightdiv
                                .append($option
                                    .attr("data-isshow", col.isshow)
                                    .attr("data-gen", col.gen.toLowerCase()));
                            else $leftdiv.append($option);
                        }
                        if (col.join) {
                            var joinobj = me.getColumnModel(col.joinindex);
                            $option.attr("data-join", joinobj.as ? joinobj.as : joinobj.fieldname);
                            $option.html($option.html() + "[合并:" + joinobj.title+"]");
                        }
                    } else {
                        $leftdiv.append($option);//如果没有找到配置项说明不在表格字段里
                    }
                    //总结性显示
                    var text = $option.text();
                    if ($option.attr("data-isshow") == "false") text += "[隐]";
                    if ($option.attr("data-gen")) text += "[key]";
                    $option.html(text);

                }
                $page.append("<div style='clear:both;'><button class='savebtn btn-default'>保存</button></div>");
                return $("<div class='yui-datagrid-settingpage'></div>").append($page).get(0).outerHTML;
            },
            /**
             * 创建自定义查询的html代码段
             * @private
             * @returns {*|string}
             */
            queryHtml:function(option) {
                var me = this;
                if(me.morequery){
                    me.morequery.setHoldData(me.condition);
                    return me.morequery.Component;
                }
                if(!option)option={};
                //var $page = $("<div class='yui-datagrid-settingpage'></div>");
                me.morequery=new Ladder.MoreQuery({
                    id:me.settings.id,
                    relation:"and",
                    single:true,
                    take:"json",
                    store:"local,server",
                    onQuery:option.onQuery||function(querycondtion){
                        me.multiSelectData = new Object();
                        me.condition.forms = JSON.stringify(querycondtion);
                        me.condition.pager = null;
                        me.loadRemote();
                    },
                    onReset:option.onReset||function(){
                        me.multiSelectData = new Object();
                        me.setCondition(me.morequery.holdData,false);
                        me.loadRemote();
                    }
                });
                var fc = [];
                if(me.fullColumns){
                    me.fullColumns.forEach(function(item){
                        if(item.isshow===0||item.isshow===false)return;
                        fc.push(item);
                    });
                }
                me.morequery.addField(fc);
                me.morequery.loadTemplate();
                me.morequery.setHoldData(me.condition);
                return me.morequery.Component;
                //return "<div class='yui-datagrid-settingpage'></div>";
            },
            /**
             * 列排序
             * @param index
             * @option 升序/降序  默认升序
             */
            handsort:function(index,option){
                var me=this;
                var array=new Array();
                var selecttd=me.datagrid.find("tbody tr td:nth-child("+index+")");
                var sorttype=false;
                if(option) option=1;
                else option=-1;
                selecttd.each(function(){
                    var $this=$(this);
                    var val = $this.text();
                    if (sorttype != "string") {
                        if (/^\d*(\.)?(\d)?$/.test(val)) sorttype = "number";
                        else sorttype = "string";
                    }
                    array.push({ht:$this.html(),tr:$this.parent()});
                });
                array.sort(function(a,b){
                    if(sorttype=="number"){a.ht=a.ht*1;b.ht= b.ht*1;}
                    if(sorttype=="date"){
                        a.ht=new Date(a.ht.replace(/-/g,"/"));
                        b.ht=new Date(b.ht.replace(/-/g,"/"));
                    }
                    if(a.ht>b.ht) {return option;}
                    if(a.ht==b.ht) {return 0;}
                    if (a.ht < b.ht) { return option * -1; }
                    return 0;
                });
                for(var i=0;i<array.length;i++)me.datagrid.append(array[i].tr);
            },
            /**
             * 处理表格宽度拉伸
             * @private
             * @returns {}
             */
            handColumnResize:function(){
                var me =this;
                var $view=$(me.settings.parentEL).find(".columnresize");//自定义拖动父组件
                $view.find(".rchandle").off();
                $view.empty();
                var height=$(me.datagrid).height();
                var top=$(me.datagrid).offset().top-22;
                $(me.datagrid).find("tbody tr:eq(0) td:gt(0)").each(function(index){
                    var $td=$(this);
                    var $rc=$("<div class='rchandle' data-index='"+index+"'><div>");
                    var tdoffset=$td.offset();
                    $rc.css({
                        top:top,
                        left:tdoffset.left,
                        height:height
                    });
                    $rc.mousedown(function(e){
                        var rc_left=e.pageX -$(this).offset().left;
                        $(document).on("mousemove", function(ev) {
                            $rc.css("left", ev.pageX - rc_left);
                            setTimeout(function() {
                                var d_left = $(me.datagrid).find("tr td:nth-child(" + (index + 1) + ")").offset().left + 6;
                                $(me.datagrid).find("tr td:nth-child(" + (index + 1) + ")").attr("width", ev.pageX - rc_left - d_left + "px");
                                setTimeout(function() {
                                    var nheight = $(me.datagrid).height();
                                    $(me.datagrid).find("tbody tr:eq(0) td:gt(0)").each(function(index) {
                                        var $rc = $(".rchandle[data-index='" + index + "']");
                                        var tdoffset = $(this).offset();
                                        $rc.css({
                                            top: top,
                                            left: tdoffset.left,
                                            height: nheight
                                        });
                                    });
                                });
                            });
                        });
                    });
                    $view.append($rc);
                });

            },
            /**
             * 取表头列数
             * @returns {*}
             */
            getHeaderCount: function () {
                var me = this;
                if (me.settings.thType == -1) {
                    if (!me.gridhead)return 0;
                    var childrens = me.gridhead.find("thead tr:first").children();
                    var count = 0;
                    for (var i = 0; i < childrens.length; i++) {
                        var size = $(childrens[i]).prop("colspan");
                        count += size;
                    }
                    return count;
                }
                return me.datagrid.find("tbody tr:first").children().length;
            },
            /**
             * 添加隐藏行
             */
            addHiddenRow:function(){
                var me=this;
                var $thead=me.gridhead.find("thead");
                if(me.settings.thType==-1&& $thead.find(".hiddenRow").length<1){
                    var $tr=$("<tr class='hiddenRow'></tr>");
                    var index=0;
                    $thead.find("tr:eq(0) th").each(function(){
                        var td=$(this);
                        var size=td.prop("colspan");
                        for(var i=0;i<size;i++){
                            index++;
                            $tr.append("<td data-index='"+index+"'></td>");
                        }
                    });
                    $thead.append($tr);
                }
            },
            /**
             * 设置表头标题
             * @param html
             */
            setHeaderHtml:function(html){
                var me=this;
                if(me.gridhead){
                    me.runstatus.B_TH=false;
                    me.gridhead.find("thead").append(html);
                    me.addHiddenRow();
                }
            },
            setHead:function(headData){
                if(!headData)return;
                var me=this;
                me.settings.autoColumnModel=false;
                var $head=me.datagrid.find("thead").empty();
                var uuid=Ladder.timecode();
                var ColumnModels=[];
                writeHead(headData,0);
                function writeHead(data,level,father){
                    data.forEach(function(item){
                        var $tr = $head.find("tr[data-rownum='"+level+"']");
                        if($tr.length<1){
                            $tr=$("<tr data-rownum='"+level+"'></tr>").appendTo($head);
                            if(father){
                                father.parent().find("th:lt("+father.index()+")").each(function(){
                                    $tr.append($(this).clone().attr("data-remove",1));
                                });
                            }
                        }
                        var $th=$("<th>"+item.title+"</th>").attr("id",uuid++);
                        if(item.width)$th.css("width",item.width);
                        if(father)$th.attr("data-father",father.attr("id"));
                        $tr.append($th);
                        if(item.columns){
                            increase($th,item.columns.length);
                            writeHead(item.columns,level+1,$th);
                        }else{
                            $th.attr("data-model",1).data("modelData",item);
                            ColumnModels.push(item);
                            var $next=$tr.next();
                            while ($next.length>0){
                                $next.append($th.clone().attr("data-remove",1));
                                $next=$next.next();
                            }
                        }
                    });
                    function increase($pth,size){
                        if(size<2)return;
                        var old = $pth.prop("colspan");//当期的合并数
                        var p = $pth.attr("data-father");//父级对象
                        $pth.prop("colspan",old+size-1);
                        if(p){
                            increase($head.find("#"+p),size);
                        }
                    }
                }
                //合并行
                $head.find("[data-remove=1]").each(function(){
                    var $this = $(this);
                    var $pre = $head.find("#"+$this.attr("id")+"[data-model=1]");
                    $this.remove();
                    $pre.prop("rowspan",$pre.prop("rowspan")+1);
                });
                me.setColumnModel(ColumnModels);
                me.rewriteHead(false);
            },
            /**
             * 导出数据,2015-10-17后加
             * @returns {*}
             */
            exportDate:function(option,url){
                console.log(option);
                var me=this;
                var $frame=me.runstatus.ToLink[0].contentDocument;
                $frame.open();
                $frame.write('<form method="post" action="" id="exportform"></form>');
                $frame.close();
                var $form=$("#exportform",$frame);
                if(!url)url=URLS.URL_ExportToExcel;
                $form.attr("action",Ladder.Service.parseUrl(url));
                var model=$("<input type='hidden' name='model' id='model'>");
                $form.append(model);
                var cm=me.getHeadModelData();
                if(option==0){
                    var first=cm.columnModel[0];
                    me.datagrid.find("tbody tr").each(function(){
                        var crow=[];
                        var $ctr=$(this);
                        for(var i=0;i<first.length;i++){
                            var content=$ctr.find("td[data-modelindex='"+first[i].modelindex+"']").text();
                            crow.push({row:1,col:1,value:content});
                        }
                        cm.columnModel.push(crow);
                    });
                }else{//全部导出
                    if( !me.settings.queryData || (!me.settings.queryData.tableName)){
                        layer.msg("对不起,当前数据表格不允许全部数据导出");
                        return;
                    }
                    var tableName=$("<input type='hidden' name='tableName' id='tableName'>").val(Ladder.getType(me.settings.queryData)=="Object"?me.settings.queryData.tableName:"");


                    var condition=$("<input type='hidden' name='condition' id='condition'>").val(Ladder.getType(me.condition.forms)=="Object"?JSON.stringify(me.condition.forms):me.condition.forms);
                    var param=$("<input type='hidden' name='param' id='param'>").val(Ladder.getType(me.settings.queryData)=="Object"?me.settings.queryData.param:"");
                    $form.append(tableName).append(condition).append(param);
                }
                model.val(JSON.stringify(cm));
                $form.submit();
                //var param = me.settings.queryData;
                //param.condition = me.condition.forms;
                //param.columns = me.condition.columnString;
                //param = $.param(param);
                //var url = Ladder.Service.parseUrl(URLS.URL_ExportToExcel);
                //if (param) url += "?" + param;
                //if (url) {
                //    me.runstatus.ToLink.attr("src", "");
                //    me.runstatus.ToLink.attr("src", url);
                //} else {
                //    layer.msg("当前条件下不容许导出");
                //}
                //return url;
            },
            /***
             * 获取表格表头的二维模型数据
             * @returns {{}}
             */
            getHeadModelData:function(){
                var me=this;
                var cm={};
                var columnModel=[];//二维数组模型
                //如果是自定义的数据，
                if(me.settings.thType==-1){
                    me.gridhead.find("thead").find("tr:not(.hiddenRow)").each(function(){
                        var $tr=$(this);
                        var row=$tr.index();//行号
                        if(columnModel.length<=row)columnModel.push([]);//当前未被追加，则推一个
                        var col=getColIndex(row,0);//开始行号以0，顺序扫描
                        $tr.find("th").each(function(){
                            var $td=$(this);
                            var colspan=$td.prop("colspan");
                            var rowspan=$td.prop("rowspan");
                            col=getColIndex(row,col);
                            for(var i=0;i<rowspan;i++){//跨行赋值
                                if(i>0){
                                    if(columnModel.length<=row+i)columnModel.push([]);
                                    columnModel[row+i][col]={value:$td.text(),col:0,row:0}
                                }else{//当前行
                                    columnModel[row][col]={value:$td.text(),col:colspan,row:rowspan}
                                    if(row==0){//如果是首行的，转载data-model
                                        columnModel[row][col].modelindex=me.datagrid.find("tbody tr:first td:eq("+col+")").data("modelindex");
                                    }
                                }
                            }
                            for(var i=colspan-1;i>0;i--){//跨列赋值
                                columnModel[row][col+i]={value:$td.text(),col:0,row:0};
                                if(row==0){//如果是首行的，转载data-model
                                    columnModel[row][col+i].modelindex=me.datagrid.find("tbody tr:first td:eq("+col+i+")").data("modelindex");
                                }
                            }
                            col+=colspan;
                        });
                    });
                    cm.type=1;
                    //获取列号
                    function getColIndex(x,y){
                        if(columnModel[x]==undefined) return 0;
                        while(columnModel[x][y]!=undefined)y++;
                        return y;
                    }

                }else{
                    columnModel.push([]);
                    for(var i=0;i<me.columnModel.length;i++){
                        columnModel[0][i]={
                            row:1,col:1,
                            value:me.columnModel[i].title,
                            fieldname:me.columnModel[i].fieldname,
                            modelindex:i
                        }
                    }
                    cm.type=0;
                }
                cm.columnModel=columnModel;
                return cm;

            },
            /**
             * 取消排序
             */
            cleanSort:function(){
                var me=this;
                var tbody=me.datagrid.find("tbody");
                var doc=$(me.datagrid.parents()[4]);
                $(doc).on("click",function(){
                    var th= me.datagrid.find("thead tr th");
                    var tr= me.datagrid.find("tbody tr");
                    if(th.hasClass("headerSortDown"))th.removeClass("headerSortDown");
                    if(th.hasClass("headerSortUp"))th.removeClass("headerSortUp");
                    if(tr.hasClass("currentSelect"))tr.removeClass("currentSelect")
                });
            },
            /***
             * 跨行合并
             * @param index 列号
             */
            spanRow:function(index){
                if(Ladder.getType(index)=="String"){
                    index = this.findModelIndex(index);
                }
                if(Ladder.getType(index)=="Number"){
                    var $tds= this.datagrid.find("tbody td[data-modelindex='"+index+"']");
                    var i=0;
                    while(i<$tds.length){
                        var rowspannum = rowcount(i);
                        $($tds[i]).attr("rowspan",rowspannum-i+1);
                        i=rowspannum+1;
                    }
                    //this.datagrid.find("tbody td[data-modelindex='"+index+"'].js-spanrow").remove();
                    function rowcount(no){
                        var value=$($tds[no]).html();
                        while(value==$($tds[no+1]).html()){
                            $($tds[no+1]).remove();
                            //.addClass("js-spanrow");
                            no++;
                        }
                        return no;
                    }
                }
            },
            //设置子视图的配置
            setSubviewConfig:function(subviewName,settings){
                if(!this.subview)this.subview={};
                this.subview[subviewName]=settings;
            },
            /***
             * 加载皮肤
             * @param skin 皮肤的css库路径
             */
            loadSkin:function(skin) {
                Ladder.include(skin);
            },
            /***
             * 冻结行列的表格处理
             * @private
             */
            fixTable:function () {
                var me=this;
                var $el=$(me.settings.parentEL);
                var $Head=$el.find(".yui-datagrid-body-head").empty().hide();
                var $Data= $el.find(".yui-datagrid-body-data");
                var $tablebody=$el.find(".yui-datagrid-body");
                if ($tablebody.height() >= me.datagrid.height() && $tablebody.width() >= me.datagrid.width()){
                    $Data.offset($tablebody.offset());
                    return;
                }
                var HeadHeight = me.datagrid.find("thead").height()+2;//表格的边框宽度
                $Head.show();
                var $Corner=$el.find(".yui-datagrid-body-corner");
                var $Columns= $el.find(".yui-datagrid-body-columns");

                var width=me.settings.width;
                var height=$(me.settings.parentEL).find(".yui-datagrid-body").height();
                //首行
                var $HeadTableClone = me.datagrid.clone(true);
                $Head.append($HeadTableClone);
                $Head.css("height", HeadHeight);
                if(me.settings.freeze>0){
                    var $CorneTableClone = me.datagrid.clone(true);
                    $Corner.empty().append($CorneTableClone).show();
                    var $ColumnTableClone = me.datagrid.clone(true);
                    $Columns.empty().append($ColumnTableClone).show();
                    $Corner.css("height", HeadHeight);
                    var ColumnsWidth = 0;
                    var ColumnsNumber = 0;
                    $Columns.find("tr:last td:lt(" + me.settings.freeze + ")").each(function () {
                        ColumnsWidth += $(this).outerWidth(true);
                        ColumnsNumber++;
                    });
                    ColumnsWidth += 2;
                    var ie = Ladder.browserversion();
                    if (ie) {
                        switch (ie) {
                            case "7.0":
                                if (ColumnsNumber >= 3) ColumnsWidth--;
                                break;
                            case "8.0":
                                if (ColumnsNumber >= 2) ColumnsWidth--;
                                break;
                        }
                    }
                    $Columns.width(ColumnsWidth);
                    $Corner.width(ColumnsWidth);
                    $Columns.height(height-17);
                }
                $Data.off("scroll").scroll(function () {
                    $Head.scrollLeft($(this).scrollLeft());
                    $Columns.scrollTop($(this).scrollTop());
                }).scrollTop(0).scrollLeft(0);

                $Head.width(width-17);
                $Data.css({"width": width, "height": height});
                ////修正宽度
                //if ($Head.width() > $Corner.find("table").width()) {
                //    $Head.css("width",$Corner.find("table").width());
                //    $Data.css("width",$Corner.find("table").width()+20);
                //}
                ////修正高度
                //if ($Columns.height() > $Columns.find("table").height()) {
                //    $Columns.css("width",$Columns.find("table").height());
                //    $Data.css("height",$Corner.find("table").height()+20);
                //}
                var $container=$el.find(".yui-datagrid-body-container").css({"width": width, "height": height});
                $Corner.offset($container.offset());
                $Head.offset($container.offset());
                $Columns.offset($container.offset());
                $Corner.offset($container.offset());
                $Data.offset($container.offset());
            },
            /**
             * 搜索关键词
             * @param word
             * @param fieldname
             */
            search:function(word,fieldname){
                var me=this;
                if(word==undefined||(word+"").length<1)me.datagrid.find("tbody tr").show();
                else{
                    var index=-1;
                    if(fieldname){
                        var index=me.findModelIndex(fieldname);
                        if(index<0)return;
                    }
                    me.datagrid.find("tbody tr").each(function() {
                        var text="";
                        if(index>-1){
                            text = $(this).find("td[data-modelindex]").text();
                        }else{
                            text = $(this).text();
                        }
                        if (text.indexOf(word) > -1) {
                            $(this).show();
                        } else $(this).hide();
                    });
                }
            }
        };
        return Ladder;
    }
    if(typeof define === "function" && define.amd){
        require.config({
            paths: {
                'form': 'ladder-form'
            }
        });
        define(['form'],__functionForGrid);
    }else{
        __functionForGrid();
    }
})();